JavaScript: Basic Syntax

  1. Variables
    1. Do not have to be declared but should
    2. Identifiers can be any combination of letters, digits, underscore, or $ but must not start with a digit or be a reserved word
    3. Declare variable with let - no data type required because JS is a loosely-typed language
      let x;
      
    4. A variable's data type can change based on what it is assigned (dynamic typing)
      x = 5;       // number
      x = "cool";  // string
      x = true;    // boolean
      
    5. Data types
      1. string - can be delimited with 'single' or "double" quotes
      2. number - 56 or 9.2 (no distinction between int and double)
      3. boolean - true or false
      4. object - many built-in objects like document, and you can create your own
      5. array - collection of values
    6. Constants - variables that cannot be re-assigned
      const PI = 3.142;
      
  2. Comments
    // Single line
    
    /* Multi-
       line */
    
  3. Arithmetic
    1. Same as C++:  +  -  *  /  %
    2. Be careful when using + which also performs string concatenation
      x = 2 + 3;      // 5
      x = 2 + "3";    // "23"
      x = "2" + "3";  // "23"
      
    3. Use parseInt() or parseFloat() to convert a string into a number
      x = 2 + parseInt("3");  // 5
      x = parseFloat("2.4");  // 2.4
      x = parseInt("pig");    // NaN (Not a Number)
      
  4. Assignment and increment/decrement
    1. Assignment operators:  +=  -=  *=  /=  %=
      x = 2;
      x += 3;  // 2 + 3 = 5
      x %= 2;  // 5 % 2 = 1
      
    2. Increment and decrement operators:  ++  --
      x = 2;
      x++;   // 3
      
  5. Relational operators
    1. Same as C++:  ==  !=  <  <=  >  >=
      10 > 9      // true
      "10" > 9    // true (LHS converted to number first)
      "10" > "9"  // false (charCode of 1 < charCode of 9)
      
    2. Strict equals (and not equals): === !== for comparing the value and type
      x = 5;
      x == 5;     // true
      x == "5";   // true
      x === 5;    // true
      x === "5";  // false (x is a number, not a string)
      
    3. Truthy and falsy
      // All evaluate to true
      if (true)
      if (123)
      if ("blah")
      
      // All evaluate to false
      if (false)
      if (null)
      if (undefined)
      if (0)
      if (NaN)
      if ("")
      
  6. Logical operators
    1. And and Or same as C++:  &&  ||
      // Evaluates to true if both simple expressions are true
      if (x < 20 && y != 2)
      
    2. Not operator same as C++:  !
      // Using the not operator is generally not preferred
      if (!(x < 20))
      
      // simplfied to
      if (x >= 20)