3. Basic JavaScript #

Created Wednesday 08 July 2020

Data types #

Popularity Name Used for Comment
1 string both strings, characters Unicode OK
2 number integers and floats
3 boolean boolean values true, false are keywords
4 object Made of primitives, objects
5 undefined default value for uninitialized variable is an object
6 null sentinel value marking absence is an object
7 symbol Store memory location
8 bigint Number with arbitrary precision added ES2020
  1. number - For both integers and floats.
  2. bigint
  3. string - both kinds of quotes are OK, you can even use backticks. Concatenation using +. Strings can be like numbers(and vice versa). e.g. '2.3'*2 = 4.6. Escape character same as C++. Strings can span multiple lines.
  4. boolean(true/false)
  5. Symbol
  6. undefined - not been assigned(garbage values are avoided this way)
  7. null
  8. object - everything except the primitives is an object, including functions, arrays etc.

Note:

String #

Variables #

Note:

  1. Uninitialized variables store the value undefined😁️. Example: let x; console.log(x) // undefined
  2. Declarations can be chained. i.e let x = 2, y = [1, 2], z = 3;.
  3. Variables cannot be redeclared, except for var.
  4. Avoid using var in new codebases.
  5. Internally, var, let, const, function, class, function _are all hoisted. But only var, function and function_`are allocated memory(set to`undefined).
  6. JavaScript has 4 scopes - local, enclosing, global, builtin. Same as python3. Discussed in detail
  7. All inner scopes can read/write to variables of outer scope. Just like C++.

Variable naming rules #

var vs let #

Hoisting(JS feature) #

Note: temporal dead zone does correlate with sections of the code, but it’s actually a time period.

Bad code

Standard IO #

Output #

Input #

Operators #

Code Structure #

Conditionals #

Loops #

Functions #

Function types and syntax #

  1. Named function - just function.
    function foo(bar1, bar2)
    {
    // code
    }
    
  2. Anonymous functions - unhoisted. Use case - as a functor, an IIFE
    x.sort( function (a) { return Number(a); }) // functor as sorting criteria
        // Don't call the functor, just specify it.
    
        // IIFE - Immediately Invoked Function Expression
        (
        function(bar) { /_ code _/ }(option1)
        )(option2)
        // You have two option, use (option1) or (option2) depending on the situation.
        // Enclosing () are a must - They prevent namespace pollution
    
  3. Lambda - passable anonymous functions. FIXME: can’t have both.
    let x = function() { // storing
        return 2;
    };
    
    x(); // calling
    
  4. Inner functions - have their own content(scope). Not invocable outside parent function. Chain as many as you like.
    function f()
    {
        function g() { /_code_/ }
        
        g() // invocation - OK
    
        function k() { /* code */ } // so called 'sibling' function
    }
    
    g()// Error - g not defined