JS cheatsheet

Basic overview

JavaScript has primitives, objects and functions. All of them are values. All are treated as objects, even primitives.

Primitives

Number, boolean, string, undefined and null are primitives.

Number

  • Numbers inherit methods from the Number.prototype object. Methods can be called on numbers:

    1
    2
    (123).toString();  //'123'
    (1.23).toFixed(1); //'1.2'
  • Global functions for converting to numbers : parseInt(), parseFloat() and Number():

    1
    2
    3
    4
    5
    parseInt('1')       //1
    parseInt('text') //NaN
    parseFloat('1.234') //1.234
    Number('1') //1
    Number('1.234') //1.234
  • Invalid arithmetic operations or invalid conversions will not throw an exception, but will result in the NaN “Not-a-Number” value. isNaN() can detect NaN.

  • The + operator can add or concatenate.

    1
    2
    3
    1 + 1      //2
    '1' + '1' //'11'
    1 + '1' //'11'

String

A string stores a series of Unicode characters. The text can be inside double quotes “” or single quotes ‘’.

  • Strings have methods like : substring(), indexOf() and concat() .

    1
    2
    3
    'text'.substring(1,3) //ex
    'text'.indexOf('x') //2
    'text'.concat(" end") //text end
  • (ES6) You can pad the current String with another String via String.prototype.padStartand String.prototype.padEnd

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // padStart
    const cardNumber = '1234567812345678';
    const last3Digit = cardNumber.slice(-3);
    const maskedCardNumber = last3Digit.padStart(16, 'X');
    console.log(maskedCardNumber); // Output: "XXXXXXXXXXXXX678"
    // padEnd
    const loremIpsum = 'Lorem Ipsum is simply dummy text of the printing and';
    const loremIpsumWithDots = loremIpsum.padEnd(loremIpsum.length+3, '.');
    console.log(loremIpsumWithDots);
    // Output: Lorem Ipsum is simply dummy text of the printing and...
  • (ES6) String interpolation can also be achieved with ${nameVar}

    1
    2
    3
    4
    5
    const name = 'Angeles';
    const hobby = 'listening to music';
    const sayHello = 'Hello, my name is ${name}. My hobby is ${hobby}.';
    console.log(sayHello);
    // Output: Hello, my name is Angeles. My hobby is listening to music.
  • Strings, like all primitives, are immutable. For example concat() doesn’t modify the existing string but creates a new one.

Boolean

A boolean has two values : true and false.

  • The language has truthy and falsy values.

    • false, null, undefined, (empty string), 0 and NaN are falsy.
    • All other values, including all objects, are truthy.
  • Evaluation:

    • Truthy value is evaluated to true when executed in a boolean context.
    • Falsy value is evaluated to false.
      1
      2
      3
      4
      5
      6
      let text = '';
      if(text) {
      console.log('This is true');
      } else {
      console.log('This is false');
      }

Objects

  • An object is a dynamic collection of key-value pairs.

    • key: string
    • value: primitive, object, or function
  • Create an object

    1
    2
    3
    4
    let obj = {
    message : 'A message',
    doSomething : function() {}
    }
  • Manage properties:

    1
    2
    3
    4
    let obj = {}; //create empty object
    obj.message = 'A message'; //add property
    obj.message = 'A new message'; //edit property
    delete object.message; //delete property
  • Objects are hash-maps. A simple hash-map can be created using `Object.create(null)`` :

    1
    2
    3
    4
    let spanish = Object.create(null);
    spanish['yes'] = 'si';
    spanish['no'] = 'no';
    spanish['yes']; //'si'
  • Immutable object: use Object.freeze() .
    Object.keys() can be used to iterate over all properties.

    1
    2
    3
    4
    5
    6
    function logProperty(name){
    console.log(name); //property name
    console.log(obj[name]); //property value
    }

    Object.keys(obj).forEach(logProperty);
  • (ES6) Iterate objects: use Object.values for direct access and Object.entries for enumerables

    1
    2
    3
    4
    5
    6
    7
    8
    const objectDummy = {
    name: 'dummy',
    isAvailable: false
    };
    Object.values(objectDummy);
    // Output: ['dummy', false]
    Object.entries(objectFoo);
    // Output: [['name', 'dummy'], ['isAvailable', false]]

Primitives vs. Objects

  • Primitives are treated like objects, in the sense that they have methods but they are not objects.
  • Primitives are immutable
  • Objects are mutable.

Variables

  • var
    • declares and optionally initializes a variable
    • default value = undefined
    • have a function scope
  • let
    • has block scope
  • const
    • cannot be reassigned (constructor)
    • its value can still be mutable via set properties
    • has a block scope

Notes:

  • const freezes the variable
  • Object.freeze() freezes the object
  • The scope of a variable declared outside any function is global.

Array

JavaScript has array-like objects. An array is implemented using an object.

  • Elements are accessed using their indices
  • Indices are converted to strings and used as names for retrieving values
  • Removing values from the array with delete will leave holes. splice() can be used to avoid the problem, but it can be slow.
    1
    2
    3
    4
    let arr = ['A', 'B', 'C'];
    delete arr[1];
    console.log(arr); // ['A', empty, 'C']
    console.log(arr.length); // 3
  • (ES6) You can check the content with Array.prototype.includes
    1
    2
    3
    4
    5
    [1, 2].includes(1); // true
    [1, 3].includes(2); // false
    var foo = 'var';
    foo.includes('v'); // true
    foo.includes('V'); // false
  • Note: Stack and queue can easily be implemented using the array methods
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    let stack = [];
    stack.push(1); // [1]
    stack.push(2); // [1, 2]
    let last = stack.pop(); // [1]
    console.log(last); // 2

    let queue = [];
    queue.push(1); // [1]
    queue.push(2); // [1, 2]
    let first = queue.shift();//[2]
    console.log(first); // 1

Functions

Definition

  • Objects which represent independent units of behavior.
  • Functions can be:
    • assigned to variables
    • stored in objects or arrays
    • passed as an argument to other functions
    • returned from functions.

There are three ways to define a function:

  • Function Declaration (aka Function Statement)
    • function is the first keyword on the line
    • it must have a name
    • it can be used before definition. Function declarations are moved, or “hoisted”, to the top of their scope.
      1
      function doSomething() {}
  • Function Expression (aka Function Literal)
    • function is not the first keyword on the line
    • the name is optional (anonymous function expression)
    • it needs to be defined, then it can execute
    • it can auto-execute after definition (called “IIFE” Immediately Invoked Function Expression)
      1
      let doSomething = function() {}
  • Arrow Function
    • creates an anonymous function expression
    • Arrow functions don’t have their own this and arguments
      1
      let doSomething = () = > {};

Invocation

  • Function form
    1
    doSomething(arguments)
  • Method form
    1
    2
    theObject.doSomething(arguments)
    theObject['doSomething'](arguments)
  • Constructor form
    1
    new doSomething(arguments)
  • Apply form
    1
    2
    doSomething.apply(theObject, [arguments])
    doSomething.call(theObject, arguments)
  • Bind form
    1
    2
    let doSomethingWithObject = doSomething.bind(theObject);
    doSomethingWithObject();
    Functions can be invoked with more or fewer arguments than declared in the definition. The extra arguments will be ignored, and the missing parameters will be set to undefined.

Function pseudo-parameters

  • this
    • represents the function’s contex
    • only functions defined with the function keyword have their own this contex
    • its value depends on how the function was invoked
      1
      2
      3
      function doSomething(){
      console.log(this)
      }
Form this
Function window/undefined
Method theObject
Constructor the new object
apply theObject
bind theObject
  • arguments

    • The arguments pseudo-parameter gives all the arguments used at invocation.
    • It’s an array-like object, but not an array. It lacks the array methods.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      function reduceToSum(total, value){
      return total + value;
      }

      function sum(){
      let args = Array.prototype.slice.call(arguments);
      return args.reduce(reduceToSum, 0);
      }

      sum(1,2,3);
    • An alternative is the new rest parameters syntax. This time args is an array object.
      1
      2
      3
      4
      function sum(...args){
      return args.reduce(reduceToSum, 0);
      }
      return;
    • A function with no return statement returns undefined. Pay attention to the automatic semi-colon insertion when using return. The following function will not return an empty object, but rather an undefined one. To avoid the issue, use { on the same line as return;
      1
      2
      3
      4
      function getObject(){ 
      return {}
      }
      getObject()

Dynamic Typing

  • JavaScript has dynamic typing

    1
    2
    3
    4
    5
    6
    7
    function log(value){
    console.log(value);
    }

    log(1);
    log('text');
    log({message : 'text'});
    • Values have types
    • Variables do not have types
    • Types can change at run time
  • The `typeof()`` operator can check the type of a variable.

    1
    2
    3
    4
    5
    6
    7
    8
    let n = 1;
    typeof(n); //number

    let s = 'text';
    typeof(s); //string

    let fn = function() {};
    typeof(fn); //function

A Single Thread

  • The main JavaScript runtime is single threaded.
  • 2 functions can’t run at the same time.
  • The runtime contains an Event Queue which stores a list of messages to be processed.
    • There are no race conditions, no deadlocks.
    • However, the code in the Event Queue needs to run fast. Otherwise the browser will become unresponsive and will ask to kill the task.

Exceptions

  • JavaScript sometimes has a preference for silent errors.
  • The next code will not throw an exception when I try to modify a frozen object:
    1
    2
    let obj = Object.freeze({});
    obj.message = 'text';
  • Strict mode eliminates some JavaScript silent errors. use strict; enables strict mode.

Prototypes

Prototype patterns

  • Types

    • Object.create()
    • Constructor function
    • class build objects over the prototype system
  • Build

    • classic
      1
      2
      3
      4
      5
      6
      7
      8
      9
      //the __proto__ property of `specializedService` points to the service object
      let service = {
      doSomething : function() {}
      }
      //build a service which has the service object as its prototype
      let specializedService = Object.create(service);
      console.log(specializedService.__proto__ === service); //true
      // it inherits the method
      specializedService.doSomething();
    • with Class
      1
      2
      3
      4
      5
      6
      7
      8
      9
      class Service {
      doSomething(){}
      }

      class SpecializedService extends Service {
      }

      let specializedService = new SpecializedService();
      console.log(specializedService.__proto__ === SpecializedService.prototype);
      • all methods defined in the Service class will be added to the Service.prototype object
      • instances of the Service class will have the same prototype Service.prototype object
      • all instances will delegate method calls to the Service.prototype object
      • methods are defined once on Service.prototype and then inherited by all instances

Prototype chains

Objects inherit from other objects. Each object has a prototype and inherits their properties from it.

When you request a property which the object does not contain, JavaScript will look down the prototype chain until it either finds the requested property, or until it reaches the end of the chain.

Functional Patterns

JavaScript has first class functions and closures. These are concepts that open the way for Functional Programming in JavaScript. As a result, higher order functions are possible.

  • Closure is an inner function that has access to the parent function’s variables, even after the parent function has executed.
  • A higher order function is a function that:
    • takes another function as an input
    • returns a function
    • does both