🏠 JavaScript Basics

By Robert Laing

Learning coding is like playing cards — you learn the rules, then you play, then you go back and learn the rules again, then you play again. — Mozilla’s Web Audio API page

The web of Web APIs

There are an overwhelming number of Web APIs available, of different vintages and browser support levels.

A reason I’m taking these notes and writing tests is I’ve often found myself having to relearn stuff to do coding problems I’d already done in the past. Often with JavaScript, I’d find everything had changed, eg using fetch instead of XMLHttpRequest.

Name-object pairs

A critical aspect of a programming language is the means it provides for using names to refer to computational objects. We say that the name identifies a variable whose value is the object. In the Scheme dialect of Lisp, we name things with define. — Structure and Interpretation of Computer Programs

Whereas lisp simply has

(define a 2)

JavaScript has let and const (I’m ignoring the deprecated var). As explained in object literals and array literals, any number of variables can be added to an object or array even if it is defined by const.

Using destructuring to swap variables

JavaScript has the handy destructuring syntax which makes packing and unpacking compound variables easy.

Swapping the values in two variables in many programing languages involves creating a temporary variable and doing this with three assignment statements. Destructuring allows us to do it in one step.

  it ("swaping values with destructuring", function() {
    let a = 1;
    let b = 2;
    [b, a] = [a , b];
    expect(a).toBe(2);
    expect(b).toBe(1);
  });

Using destructuring to set multiple variables

A line can be cut from the above example by using destructuring to assign any number of variables.

  it ("bulk setting of variables with array destructuring", function() {
    let [a, b] = [1, 2];
    [b, a] = [a , b];
    expect(a).toBe(2);
    expect(b).toBe(1);
  });