JavaScript as a Second Language: A Primer

JavaScript Uses C-Like Syntax

JavaScript uses C-like syntax, making it look superficially like languages such as C, C++, C#, and Java. Some qualities of C-like syntax are as follows:

  1. Single-line comments use //; multi-line comments use /* */.

    // this is a single-line comment
    
    /*
       this
       is
       a
       multi-line
       comment
    */
    
  2. Curly braces { } denote blocks.

    // The following code is identical to what you might write in Java or C.
    while (condition1) {
      if (condition2) {
        // do a thing
      } else {
        // do a different thing
      }
    }
    
  3. Statements are terminated by semicolons, and whitespace is irrelevant.

    // Although this is unnecessarily difficult to read, it is technically
    // correct, working code:
    if(i>1){arr.push(i);return false;}else{return true;}
    
    
    // A better, clearer way to write the same thing:
    if (i > 1) {
      arr.push(i);
      return false;
    } else {
      return true;
    }
    

Declaring Functions and Variables

JavaScript has gone through a bit of a redesign recently, thanks to the update of the language known as ES2015. ES2015 introduced new ways of declaring functions and variables that rectify some bizarre behavior in the original JavaScript specification.

  1. Declaring Variables

    // New Way
    let myNumber = 42;        // use "let" the first time you declare a variable
    myNumber = myNumber + 1;  // same as myNumber += 1; no need to reuse "let"
    
    
    const myConstant = 74;    // use "const" whenever you know the value of the
                              // variable is not going to change
    
    
    // Old Way
    var myNumber = 42;        /*
                               * "var" has some bizarre edge-case scoping
                               * rules, so if using "var", declare all your
                               * variables at the top of each function, NOT
                               * when the variable is first used
                               */
    
    
    // Never-Ever Way
    myNumber = 42;            /*
                               * Technically, this will work, but it makes
                               * myNumber a global variable accessible by ALL
                               * other JavaScript files in the project.  Never,
                               * ever do this.
                               */
    
  2. Declaring Functions

    // New Way - use for non-method functions
    let myFunction = (arg1, arg2) => {
      // body of function
      return result;
    };
    
    
    // Old Way - use for methods
    function myFunction(arg1, arg2) {
      // body of function
      return result;
    }
    
    
    // Another Old Way
    var myFunction = function(arg1, arg2) {
      // body of function
      return result;
    }
    

Data Types

  1. Numbers

    let myNumber = (100 + 5 * 4) / 3 - (-2); // JavaScript uses PEMDAS, so
                                             // this evaluates to 42.
    
    
    let impossible1 = 100 / 0;               // the special value "Infinity"
    
    
    let impossible2 = 0 / 0;                 // the special value "NaN"
                                             // (short for "Not a Number")
    
  2. Strings

    // New Way
    let greeting = `Hello ${name}!`;         // ES2015 has string interpolation
    
    
    // Old Way
    let greeting = "Hello " + name + "!"     // Old JavaScript relies on + to concat
    
  3. Booleans

    let condition = !((true && false) || (1 < 0)); // Evaluates to true
    
  4. null and undefined

    // The difference between null and undefined is a bit wonky, and ultimately
    // not that consequential.  Both represent a value which is not there.
    
  5. Arrays

    let myArray = [42, "", false]; // arrays don't have to have the same data type
    let element = myArray[0];      // use square brackets to index; this is 42
    myArray[4] = "test";           // myArray is now [42, "", false, undefined, "test"]
    
  6. Objects

    /*
     * JavaScript objects are really key/value pairs, similar to what Perl and
     * Ruby call a "hash" or what Python calls a "dictionary".  The key must be a
     * string; the value can be ANYTHING, even a function!
     */
    let note = {
      "midiNumber": 60,
      "duration": "4n"
    };
    
    
    let midiNumber = note["midiNumber"]; // one way to access a value by key
    let duration = note.duration;        // another way to access a value by key
    
    
    /*
     * In this example, "transpose" is a function, but it might more aptly be
     * called a method.  If this example is starting to look like an
     * object-oriented programming paradigm, that's because it is!
     */
    let chord = {
      "notes": [note1, note2, note3],
      "transpose": function(transposeValue) {
        for (let i = 0; i < this.notes.length; i += 1) {
          let note = this.notes[i];
          note.midiNumber = note.midiNumber + transposeValue;
        }
      }
    };
    

Control Flow

JavaScript supports many common control flow statements:

Many tasks you can do with one control flow statement (e.g. foreach) can also be accomplished with another (e.g. for), so don't feel pressure to memorize the syntax for all of this. If you just know if/else if/else, for, and while, you should be able to get by just fine.