Modern JavaScript Cheatsheet

Cheatsheet for the JavaScript knowledge you will frequently encounter in mo...

README

Modern JavaScript Cheatsheet


Modern JavaScript cheatsheet
Image Credits: [Ahmad Awais ⚡️](https://github.com/ahmadawais)

If you like this content, you can ping me or follow me on Twitter :+1:

Tweet for help

Introduction


Motivation


This document is a cheatsheet for JavaScript you will frequently encounter in modern projects and most contemporary sample code.

This guide is not intended to teach you JavaScript from the ground up, but to help developers with basic knowledge who may struggle to get familiar with modern codebases (or let's say to learn React for instance) because of the JavaScript concepts used.

Besides, I will sometimes provide personal tips that may be debatable but will take care to mention that it's a personal recommendation when I do so.

Note: Most of the concepts introduced here are coming from a JavaScript language update (ES2015, often called ES6). You can find new features added by this update here; it's very well done.


Complementary Resources


When you struggle to understand a notion, I suggest you look for answers on the following resources:

- Javascript Basics for Beginners - a free Udacity course
- Google to find specific blog and resources

Table of Contents


    + Motivation
      - Short explanation
      - Sample code
      - Detailed explanation
      - External resource
    + Arrow function
      - Sample code
      - Detailed explanation
        Concision
        [this reference](#this-reference)
      - Useful resources
      - External resource
      - Useful resources
      - Sample code
      - Explanation
        Array.prototype.map()
        Array.prototype.filter()
        Array.prototype.reduce()
        Array.prototype.find()
      - External Resource
      - Sample code
      - Explanation
        Function rest parameter
      - External resources
      - Explanation
      - External resources
    + Promises
      - Sample code
      - Explanation
        Create the promise
        Promise handlers usage
      - External Resources
      - Sample code
      - External resources
      - External resources
        Named exports
        Default import / export
      - External resources
    + [JavaScript this](#-javascript-this)
      - External resources
    + Class
      - Samples
      - External resources
      - Sample Code
      - External Resources
    + Async Await
      - Sample code
      - Error handling
      - External resources
    + Truthy / Falsy
      - External resources
      - Anamorphisms
      - Catamorphisms
      - External resources
    + Generators
      - External resources
    + Static Methods
      - Short Explanation
      - Sample Code
      - Detailed Explanation
      - External resources
    + Scope

Notions


Variable declaration: var, const, let


In JavaScript, there are three keywords available to declare a variable, and each has its differences. Those are var , let and const .

Short explanation


Variables declared with const keyword can't be reassigned, while let and var can.

I recommend always declaring your variables with const by default, but with let if it is a variable that you need to mutate or reassign later.

Scope Reassignable Mutable Temporal Dead Zone
const Block No Yes Yes
let Block Yes Yes Yes
var Function Yes Yes No

Sample code


  1. ``` js
  2. const person = "Nick";
  3. person = "John" // Will raise an error, person can't be reassigned
  4. ```

  1. ``` js
  2. let person = "Nick";
  3. person = "John";
  4. console.log(person) // "John", reassignment is allowed with let
  5. ```

Detailed explanation


The [scope](#scope_def) of a variable roughly means "where is this variable available in the code".

var

var declared variables are function scoped, meaning that when a variable is created in a function, everything in that function can access that variable. Besides, a function scoped variable created in a function can't be accessed outside this function.

I recommend you to picture it as if an X scoped variable meant that this variable was a property of X.

  1. ``` js
  2. function myFunction() {
  3.   var myVar = "Nick";
  4.   console.log(myVar); // "Nick" - myVar is accessible inside the function
  5. }
  6. console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
  7. ```

Still focusing on the variable scope, here is a more subtle example:

  1. ``` js
  2. function myFunction() {
  3.   var myVar = "Nick";
  4.   if (true) {
  5.     var myVar = "John";
  6.     console.log(myVar); // "John"
  7.     // actually, myVar being function scoped, we just erased the previous myVar value "Nick" for "John"
  8.   }
  9.   console.log(myVar); // "John" - see how the instructions in the if block affected this value
  10. }
  11. console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
  12. ```

Besides, var declared variables are moved to the top of the scope at execution. This is what we call var hoisting.

This portion of code:

  1. ``` js
  2. console.log(myVar) // undefined -- no error raised
  3. var myVar = 2;
  4. ```

is understood at execution like:

  1. ``` js
  2. var myVar;
  3. console.log(myVar) // undefined -- no error raised
  4. myVar = 2;
  5. ```

let

var and let are about the same, but let declared variables

- are block scoped
- are not accessible before they are assigned
- can't be re-declared in the same scope

Let's see the impact of block-scoping taking our previous example:

  1. ``` js
  2. function myFunction() {
  3.   let myVar = "Nick";
  4.   if (true) {
  5.     let myVar = "John";
  6.     console.log(myVar); // "John"
  7.     // actually, myVar being block scoped, we just created a new variable myVar.
  8.     // this variable is not accessible outside this block and totally independent
  9.     // from the first myVar created !
  10.   }
  11.   console.log(myVar); // "Nick", see how the instructions in the if block DID NOT affect this value
  12. }
  13. console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
  14. ```

Now, what it means for *let* (and *const*) variables for not being accessible before being assigned:

  1. ``` js
  2. console.log(myVar) // raises a ReferenceError !
  3. let myVar = 2;
  4. ```

By contrast with var variables, if you try to read or write on a let or const variable before they are assigned an error will be raised. This phenomenon is often called [Temporal dead zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let) or TDZ.

Note: Technically, let and const variables declarations are being hoisted too, but not their assignation. Since they're made so that they can't be used before assignation, it intuitively feels like there is no hoisting, but there is. Find out more on this very detailed explanation here if you want to know more.


In addition, you can't re-declare a let variable:

  1. ``` js
  2. let myVar = 2;
  3. let myVar = 3; // Raises a SyntaxError
  4. ```

const

const declared variables behave like let variables, but also they can't be reassigned.

To sum it up, const variables:

- are block scoped
- are not accessible before being assigned
- can't be re-declared in the same scope
- can't be reassigned

  1. ``` js
  2. const myVar = "Nick";
  3. myVar = "John" // raises an error, reassignment is not allowed
  4. ```

  1. ``` js
  2. const myVar = "Nick";
  3. const myVar = "John" // raises an error, re-declaration is not allowed
  4. ```

But there is a subtlety : `const` variables are not [**immutable**](#mutation_def) ! Concretely, it means that *object* and *array* `const` declared variables **can** be mutated.

For objects:
  1. ``` js
  2. const person = {
  3.   name: 'Nick'
  4. };
  5. person.name = 'John' // this will work ! person variable is not completely reassigned, but mutated
  6. console.log(person.name) // "John"
  7. person = "Sandra" // raises an error, because reassignment is not allowed with const declared variables
  8. ```

For arrays:
  1. ``` js
  2. const person = [];
  3. person.push('John'); // this will work ! person variable is not completely reassigned, but mutated
  4. console.log(person[0]) // "John"
  5. person = ["Nick"] // raises an error, because reassignment is not allowed with const declared variables
  6. ```

External resource



### Arrow function

The ES6 JavaScript update has introduced arrow functions, which is another way to declare and use functions. Here are the benefits they bring:

- More concise
- this is picked up from surroundings
- implicit return

Sample code


- Concision and implicit return

  1. ``` js
  2. function double(x) { return x * 2; } // Traditional way
  3. console.log(double(2)) // 4
  4. ```

  1. ``` js
  2. const double = x => x * 2; // Same function written as an arrow function with implicit return
  3. console.log(double(2)) // 4
  4. ```

- this reference

In an arrow function, this is equal to the this value of the enclosing execution context. Basically, with arrow functions, you don't have to do the "that = this" trick before calling a function inside a function anymore.

  1. ``` js
  2. function myFunc() {
  3.   this.myVar = 0;
  4.   setTimeout(() => {
  5.     this.myVar++;
  6.     console.log(this.myVar) // 1
  7.   }, 0);
  8. }
  9. ```

Detailed explanation


Concision

Arrow functions are more concise than traditional functions in many ways. Let's review all the possible cases:

- Implicit VS Explicit return

An explicit return is a function where the return keyword is used in its body.

  1. ``` js
  2.   function double(x) {
  3.     return x * 2; // this function explicitly returns x * 2, *return* keyword is used
  4.   }
  5. ```

In the traditional way of writing functions, the return was always explicit. But with arrow functions, you can do implicit return which means that you don't need to use the keyword return to return a value.

  1. ``` js
  2.   const double = (x) => {
  3.     return x * 2; // Explicit return here
  4.   }
  5. ```

Since this function only returns something (no instructions before the return keyword) we can do an implicit return.

  1. ``` js
  2.   const double = (x) => x * 2; // Correct, returns x*2
  3. ```

To do so, we only need to remove the brackets and the return keyword. That's why it's called an implicit return, the return keyword is not there, but this function will indeed return x * 2 .

Note: If your function does not return a value (with side effects), it doesn't do an explicit nor an implicit return.


Besides, if you want to implicitly return an object you must have parentheses around it since it will conflict with the block braces:

  1. ``` js
  2. const getPerson = () => ({ name: "Nick", age: 24 })
  3. console.log(getPerson()) // { name: "Nick", age: 24 } -- object implicitly returned by arrow function
  4. ```

- Only one argument

If your function only takes one parameter, you can omit the parentheses around it. If we take back the above double code:

  1. ``` js
  2.   const double = (x) => x * 2; // this arrow function only takes one parameter
  3. ```

Parentheses around the parameter can be avoided:

  1. ``` js
  2.   const double = x => x * 2; // this arrow function only takes one parameter
  3. ```

- No arguments

When there is no argument provided to an arrow function, you need to provide parentheses, or it won't be valid syntax.

  1. ``` js
  2.   () => { // parentheses are provided, everything is fine
  3.     const x = 2;
  4.     return x;
  5.   }
  6. ```

  1. ``` js
  2.   => { // No parentheses, this won't work!
  3.     const x = 2;
  4.     return x;
  5.   }
  6. ```

this reference

To understand this subtlety introduced with arrow functions, you must know how this behaves in JavaScript.

In an arrow function, this is equal to the this value of the enclosing execution context. What it means is that an arrow function doesn't create a new this, it grabs it from its surrounding instead.

Without arrow function, if you wanted to access a variable from this in a function inside a function, you had to use the that = this or self = this trick.

For instance, using setTimeout function inside myFunc:

  1. ``` js
  2. function myFunc() {
  3.   this.myVar = 0;
  4.   var that = this; // that = this trick
  5.   setTimeout(
  6.     function() { // A new *this* is created in this function scope
  7.       that.myVar++;
  8.       console.log(that.myVar) // 1

  9.       console.log(this.myVar) // undefined -- see function declaration above
  10.     },
  11.     0
  12.   );
  13. }
  14. ```

But with arrow function, this is taken from its surrounding:

  1. ``` js
  2. function myFunc() {
  3.   this.myVar = 0;
  4.   setTimeout(
  5.     () => { // this taken from surrounding, meaning myFunc here
  6.       this.myVar++;
  7.       console.log(this.myVar) // 1
  8.     },
  9.     0
  10.   );
  11. }
  12. ```

Useful resources


- [Arrow function and lexical this](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4)

Function default parameter value


Starting from ES2015 JavaScript update, you can set default value to your function parameters using the following syntax:

  1. ``` js
  2. function myFunc(x = 10) {
  3.   return x;
  4. }
  5. console.log(myFunc()) // 10 -- no value is provided so x default value 10 is assigned to x in myFunc
  6. console.log(myFunc(5)) // 5 -- a value is provided so x is equal to 5 in myFunc

  7. console.log(myFunc(undefined)) // 10 -- undefined value is provided so default value is assigned to x
  8. console.log(myFunc(null)) // null -- a value (null) is provided, see below for more details
  9. ```

The default parameter is applied in two and only two situations:

- No parameter provided
- undefined parameter provided

In other words, if you pass in null the default parameter won't be applied.

Note: Default value assignment can be used with destructured parameters as well (see next notion to see an example)


External resource



Destructuring objects and arrays


Destructuring is a convenient way of creating new variables by extracting some values from data stored in objects or arrays.

To name a few use cases, destructuring can be used to destructure function parameters or this.props in React projects for instance.

Explanation with sample code


- Object

Let's consider the following object for all the samples:

  1. ``` js
  2. const person = {
  3.   firstName: "Nick",
  4.   lastName: "Anderson",
  5.   age: 35,
  6.   sex: "M"
  7. }
  8. ```

Without destructuring

  1. ``` js
  2. const first = person.firstName;
  3. const age = person.age;
  4. const city = person.city || "Paris";
  5. ```

With destructuring, all in one line:

  1. ``` js
  2. const { firstName: first, age, city = "Paris" } = person; // That's it !

  3. console.log(age) // 35 -- A new variable age is created and is equal to person.age
  4. console.log(first) // "Nick" -- A new variable first is created and is equal to person.firstName
  5. console.log(firstName) // ReferenceError -- person.firstName exists BUT the new variable created is named first
  6. console.log(city) // "Paris" -- A new variable city is created and since person.city is undefined, city is equal to the default value provided "Paris".
  7. ```

Note : In const { age } = person; , the brackets after const keyword are not used to declare an object nor a block but is the destructuring syntax.

- Function parameters

Destructuring is often used to destructure objects parameters in functions.

Without destructuring

  1. ``` js
  2. function joinFirstLastName(person) {
  3.   const firstName = person.firstName;
  4.   const lastName = person.lastName;
  5.   return firstName + '-' + lastName;
  6. }

  7. joinFirstLastName(person); // "Nick-Anderson"
  8. ```

In destructuring the object parameter person, we get a more concise function:

  1. ``` js
  2. function joinFirstLastName({ firstName, lastName }) { // we create firstName and lastName variables by destructuring person parameter
  3.   return firstName + '-' + lastName;
  4. }

  5. joinFirstLastName(person); // "Nick-Anderson"
  6. ```

Destructuring is even more pleasant to use with arrow functions:

  1. ``` js
  2. const joinFirstLastName = ({ firstName, lastName }) => firstName + '-' + lastName;

  3. joinFirstLastName(person); // "Nick-Anderson"
  4. ```

- Array

Let's consider the following array:

  1. ``` js
  2. const myArray = ["a", "b", "c"];
  3. ```

Without destructuring

  1. ``` js
  2. const x = myArray[0];
  3. const y = myArray[1];
  4. ```

With destructuring

  1. ``` js
  2. const [x, y] = myArray; // That's it !

  3. console.log(x) // "a"
  4. console.log(y) // "b"
  5. ```

Useful resources



Array methods - map / filter / reduce / find


Map, filter, reduce and find are array methods that are coming from a programming paradigm named [functional programming](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0).

To sum it up:

- Array.prototype.map() takes an array, does something on its elements and returns an array with the transformed elements.
- Array.prototype.filter() takes an array, decides element by element if it should keep it or not and returns an array with the kept elements only
- Array.prototype.reduce() takes an array and aggregates the elements into a single value (which is returned)
- Array.prototype.find() takes an array, and returns the first element that satisfies the provided condition.

I recommend to use them as much as possible in following the principles of functional programming because they are composable, concise and elegant.

With those four methods, you can avoid the use of for and forEach loops in most situations. When you are tempted to do a for loop, try to do it with map, filter, reduce and find composed. You might struggle to do it at first because it requires you to learn a new way of thinking, but once you've got it things get easier.

Sample code


  1. ``` js
  2. const numbers = [0, 1, 2, 3, 4, 5, 6];
  3. const doubledNumbers = numbers.map(n => n * 2); // [0, 2, 4, 6, 8, 10, 12]
  4. const evenNumbers = numbers.filter(n => n % 2 === 0); // [0, 2, 4, 6]
  5. const sum = numbers.reduce((prev, next) => prev + next, 0); // 21
  6. const greaterThanFour = numbers.find((n) => n>4); // 5
  7. ```

Compute total grade sum for students with grades 10 or above by composing map, filter and reduce:

  1. ``` js
  2. const students = [
  3.   { name: "Nick", grade: 10 },
  4.   { name: "John", grade: 15 },
  5.   { name: "Julia", grade: 19 },
  6.   { name: "Nathalie", grade: 9 },
  7. ];

  8. const aboveTenSum = students
  9.   .map(student => student.grade) // we map the students array to an array of their grades
  10.   .filter(grade => grade >= 10) // we filter the grades array to keep those 10 or above
  11.   .reduce((prev, next) => prev + next, 0); // we sum all the grades 10 or above one by one

  12. console.log(aboveTenSum) // 44 -- 10 (Nick) + 15 (John) + 19 (Julia), Nathalie below 10 is ignored
  13. ```

Explanation


Let's consider the following array of numbers for our examples:

  1. ``` js
  2. const numbers = [0, 1, 2, 3, 4, 5, 6];
  3. ```

Array.prototype.map()

  1. ``` js
  2. const doubledNumbers = numbers.map(function(n) {
  3.   return n * 2;
  4. });
  5. console.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]
  6. ```

What's happening here? We are using .map on the numbers array, the map is iterating on each element of the array and passes it to our function. The goal of the function is to produce and return a new value from the one passed so that map can replace it.

Let's extract this function to make it more clear, just for this once:

  1. ``` js
  2. const doubleN = function(n) { return n * 2; };
  3. const doubledNumbers = numbers.map(doubleN);
  4. console.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]
  5. ```

Note : You will frequently encounter this method used in combination with arrow functions

  1. ``` js
  2. const doubledNumbers = numbers.map(n => n * 2);
  3. console.log(doubledNumbers); // [0, 2, 4, 6, 8, 10, 12]
  4. ```

numbers.map(doubleN) produces [doubleN(0), doubleN(1), doubleN(2), doubleN(3), doubleN(4), doubleN(5), doubleN(6)] which is equal to [0, 2, 4, 6, 8, 10, 12] .

Note: If you do not need to return a new array and just want to do a loop that has side effects, you might just want to use a for / forEach loop instead of a map.


Array.prototype.filter()

  1. ``` js
  2. const evenNumbers = numbers.filter(function(n) {
  3.   return n % 2 === 0; // true if "n" is par, false if "n" isn't
  4. });
  5. console.log(evenNumbers); // [0, 2, 4, 6]
  6. ```

Note : You will frequently encounter this method used in combination with arrow functions

  1. ``` js
  2. const evenNumbers = numbers.filter(n => n % 2 === 0);
  3. console.log(evenNumbers); // [0, 2, 4, 6]
  4. ```

We are using .filter on the numbers array, filter is iterating on each element of the array and passes it to our function. The goal of the function is to return a boolean that will determine whether the current value will be kept or not. Filter then returns the array with only the kept values.

Array.prototype.reduce()

The reduce method goal is to reduce all elements of the array it iterates on into a single value. How it aggregates those elements is up to you.

  1. ``` js
  2. const sum = numbers.reduce(
  3.   function(acc, n) {
  4.     return acc + n;
  5.   },
  6.   0 // accumulator variable value at first iteration step
  7. );

  8. console.log(sum) // 21
  9. ```

Note : You will frequently encounter this method used in combination with arrow functions

  1. ``` js
  2. const sum = numbers.reduce((acc, n) => acc + n, 0);
  3. console.log(sum) // 21
  4. ```

Just like for .map and .filter methods, .reduce is applied on an array and takes a function as the first parameter.

This time though, there are changes:

- .reduce takes two parameters

The first parameter is a function that will be called at each iteration step.

The second parameter is the value of the accumulator variable (acc here) at the first iteration step (read next point to understand).

- Function parameters

The function you pass as the first parameter of .reduce takes two parameters. The first one (acc here) is the accumulator variable, whereas the second parameter (n) is the current element.

The accumulator variable is equal to the return value of your function at the previous iteration step. At the first step of the iteration, acc is equal to the value you passed as .reduce second parameter.

At first iteration step

acc = 0 because we passed in 0 as the second parameter for reduce

n = 0 first element of the number array

Function returns acc + n --> 0 + 0 --> 0

At second iteration step

acc = 0 because it's the value the function returned at the previous iteration step

n = 1 second element of the number array

Function returns acc + n --> 0 + 1 --> 1

At third iteration step

acc = 1 because it's the value the function returned at the previous iteration step

n = 2 third element of the number array

Function returns acc + n --> 1 + 2 --> 3

At fourth iteration step

acc = 3 because it's the value the function returned at the previous iteration step

n = 3 fourth element of the number array

Function returns acc + n --> 3 + 3 --> 6

[...] At last iteration step

acc = 15 because it's the value the function returned at the previous iteration step

n = 6 last element of the number array

Function returns acc + n --> 15 + 6 --> 21

As it is the last iteration step, .reduce returns 21.

Array.prototype.find()

  1. ``` js
  2. const greaterThanZero = numbers.find(function(n) {
  3.   return n > 0; // return number just greater than 0 is present
  4. });
  5. console.log(greaterThanZero); // 1
  6. ```

Note : You will frequently encounter this method used in combination with arrow functions

We are using .find on the numbers array, .find is iterating on each element of the array and passes it to our function, until the condition is met. The goal of the function is to return the element that satisfies the current testing function. The .find method executes the callback function once for each index of the array until the callback returns a truthy value.

Note : It immediately returns the value of that element (that satisfies the condition) if found. Otherwise, returns undefined.

External Resource



Spread operator "..."


The spread operator ... has been introduced with ES2015 and is used to expand elements of an iterable (like an array) into places where multiple elements can fit.

Sample code


  1. ``` js
  2. const arr1 = ["a", "b", "c"];
  3. const arr2 = [...arr1, "d", "e", "f"]; // ["a", "b", "c", "d", "e", "f"]
  4. ```

  1. ``` js
  2. function myFunc(x, y, ...params) {
  3.   console.log(x);
  4.   console.log(y);
  5.   console.log(params)
  6. }

  7. myFunc("a", "b", "c", "d", "e", "f")
  8. // "a"
  9. // "b"
  10. // ["c", "d", "e", "f"]
  11. ```

  1. ``` js
  2. const { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
  3. console.log(x); // 1
  4. console.log(y); // 2
  5. console.log(z); // { a: 3, b: 4 }

  6. const n = { x, y, ...z };
  7. console.log(n); // { x: 1, y: 2, a: 3, b: 4 }
  8. ```

Explanation


In iterables (like arrays)

If we have the two following arrays:

  1. ``` js
  2. const arr1 = ["a", "b", "c"];
  3. const arr2 = [arr1, "d", "e", "f"]; // [["a", "b", "c"], "d", "e", "f"]
  4. ```

arr2 the first element is an array because arr1 is injected as is into arr2. But what we want is arr2 to be an array of letters. To do so, we can spread the elements of arr1 into arr2.

With spread operator

  1. ``` js
  2. const arr1 = ["a", "b", "c"];
  3. const arr2 = [...arr1, "d", "e", "f"]; // ["a", "b", "c", "d", "e", "f"]
  4. ```

Function rest parameter

In function parameters, we can use the rest operator to inject parameters into an array we can loop in. There is already an arguments object bound to every function that is equal to an array of all the parameters passed into the function.

  1. ``` js
  2. function myFunc() {
  3.   for (var i = 0; i < arguments.length; i++) {
  4.     console.log(arguments[i]);
  5.   }
  6. }

  7. myFunc("Nick", "Anderson", 10, 12, 6);
  8. // "Nick"
  9. // "Anderson"
  10. // 10
  11. // 12
  12. // 6
  13. ```

But let's say that we want this function to create a new student with its grades and with its average grade. Wouldn't it be more convenient to extract the first two parameters into two separate variables, and then have all the grades in an array we can iterate over?

That's exactly what the rest operator allows us to do!

  1. ``` js
  2. function createStudent(firstName, lastName, ...grades) {
  3.   // firstName = "Nick"
  4.   // lastName = "Anderson"
  5.   // [10, 12, 6] -- "..." takes all other parameters passed and creates a "grades" array variable that contains them

  6.   const avgGrade = grades.reduce((acc, curr) => acc + curr, 0) / grades.length; // computes average grade from grades

  7.   return {
  8.     firstName: firstName,
  9.     lastName: lastName,
  10.     grades: grades,
  11.     avgGrade: avgGrade
  12.   }
  13. }

  14. const student = createStudent("Nick", "Anderson", 10, 12, 6);
  15. console.log(student);
  16. // {
  17. //   firstName: "Nick",
  18. //   lastName: "Anderson",
  19. //   grades: [10, 12, 6],
  20. //   avgGrade: 9,33
  21. // }
  22. ```

Note: createStudent function is bad because we don't check if grades.length exists or is different from 0. But it's easier to read this way, so I didn't handle this case.


Object properties spreading

For this one, I recommend you read previous explanations about the rest operator on iterables and function parameters.

  1. ``` js
  2. const myObj = { x: 1, y: 2, a: 3, b: 4 };
  3. const { x, y, ...z } = myObj; // object destructuring here
  4. console.log(x); // 1
  5. console.log(y); // 2
  6. console.log(z); // { a: 3, b: 4 }

  7. // z is the rest of the object destructured: myObj object minus x and y properties destructured

  8. const n = { x, y, ...z };
  9. console.log(n); // { x: 1, y: 2, a: 3, b: 4 }

  10. // Here z object properties are spread into n
  11. ```

External resources



Object property shorthand


When assigning a variable to an object property, if the variable name is equal to the property name, you can do the following:

  1. ``` js
  2. const x = 10;
  3. const myObj = { x };
  4. console.log(myObj.x) // 10
  5. ```

Explanation


Usually (pre-ES2015) when you declare a new object literal and want to use variables as object properties values, you would write this kind of code:

  1. ``` js
  2. const x = 10;
  3. const y = 20;

  4. const myObj = {
  5.   x: x, // assigning x variable value to myObj.x
  6.   y: y // assigning y variable value to myObj.y
  7. };

  8. console.log(myObj.x) // 10
  9. console.log(myObj.y) // 20
  10. ```

As you can see, this is quite repetitive because the properties name of myObj are the same as the variable names you want to assign to those properties.

With ES2015, when the variable name is the same as the property name, you can do this shorthand:

  1. ``` js
  2. const x = 10;
  3. const y = 20;

  4. const myObj = {
  5.   x,
  6.   y
  7. };

  8. console.log(myObj.x) // 10
  9. console.log(myObj.y) // 20
  10. ```

External resources



Promises


A promise is an object which can be returned synchronously from an asynchronous function (ref).

Promises can be used to avoid callback hell, and they are more and more frequently encountered in modern JavaScript projects.

Sample code


  1. ``` js
  2. const fetchingPosts = new Promise((res, rej) => {
  3.   $.get("/posts")
  4.     .done(posts => res(posts))
  5.     .fail(err => rej(err));
  6. });

  7. fetchingPosts
  8.   .then(posts => console.log(posts))
  9.   .catch(err => console.log(err));
  10. ```

Explanation


When you do an Ajax request the response is not synchronous because you want a resource that takes some time to come. It even may never come if the resource you have requested is unavailable for some reason (404).

To handle that kind of situation, ES2015 has given us promises. Promises can have three different states:

- Pending
- Fulfilled
- Rejected

Let's say we want to use promises to handle an Ajax request to fetch the resource X.

Create the promise

We firstly are going to create a promise. We will use the jQuery get method to do our Ajax request to X.

  1. ``` js
  2. const xFetcherPromise = new Promise( // Create promise using "new" keyword and store it into a variable
  3.   function(resolve, reject) { // Promise constructor takes a function parameter which has resolve and reject parameters itself
  4.     $.get("X") // Launch the Ajax request
  5.       .done(function(X) { // Once the request is done...
  6.         resolve(X); // ... resolve the promise with the X value as parameter
  7.       })
  8.       .fail(function(error) { // If the request has failed...
  9.         reject(error); // ... reject the promise with the error as parameter
  10.       });
  11.   }
  12. )
  13. ```

As seen in the above sample, the Promise object takes an executor function which takes two parameters resolve and reject. Those parameters are functions which when called are going to move the promise pending state to respectively a fulfilled and rejected state.

The promise is in pending state after instance creation and its executor function is executed immediately. Once one of the function resolve or reject is called in the executor function, the promise will call its associated handlers.

Promise handlers usage

To get the promise result (or error), we must attach to it handlers by doing the following:

  1. ``` js
  2. xFetcherPromise
  3.   .then(function(X) {
  4.     console.log(X);
  5.   })
  6.   .catch(function(err) {
  7.     console.log(err)
  8.   })
  9. ```

If the promise succeeds, resolve is executed and the function passed as .then parameter is executed.

If it fails, reject is executed and the function passed as .catch parameter is executed.

Note : If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. (Ref: MDN)


External Resources



Template literals


Template literals is an [expression interpolation](https://en.wikipedia.org/wiki/String_interpolation) for single and multiple-line strings.

In other words, it is a new string syntax in which you can conveniently use any JavaScript expressions (variables for instance).

Sample code


  1. ``` js
  2. const name = "Nick";
  3. `Hello ${name}, the following expression is equal to four : ${2+2}`;

  4. // Hello Nick, the following expression is equal to four: 4
  5. ```

External resources



Tagged template literals


Template tags are functions that can be prefixed to a template literal. When a function is called this way, the first parameter is an array of the strings that appear between the template's interpolated variables, and the subsequent parameters are the interpolated values. Use a spread operator ... to capture all of them. (Ref: MDN).

Note : A famous library named styled-components heavily relies on this feature.


Below is a toy example on how they work.
  1. ``` js
  2. function highlight(strings, ...values) {
  3.   const interpolation = strings.reduce((prev, current) => {
  4.     return prev + current + (values.length ? "<mark>" + values.shift() + "</mark>" : "");
  5.   }, "");

  6.   return interpolation;
  7. }

  8. const condiment = "jam";
  9. const meal = "toast";

  10. highlight`I like ${condiment} on ${meal}.`;
  11. // "I like jam on toast."
  12. ```

A more interesting example:
  1. ``` js
  2. function comma(strings, ...values) {
  3.   return strings.reduce((prev, next) => {
  4.     let value = values.shift() || [];
  5.     value = value.join(", ");
  6.     return prev + next + value;
  7.   }, "");
  8. }

  9. const snacks = ['apples', 'bananas', 'cherries'];
  10. comma`I like ${snacks} to snack on.`;
  11. // "I like apples, bananas, cherries to snack on."
  12. ```

External resources


Imports / Exports


ES6 modules are used to access variables or functions in a module explicitly exported by the modules it imports.

I highly recommend to take a look at MDN resources on import/export (see external resources below), it is both straightforward and complete.

Explanation with sample code


Named exports

Named exports are used to export several values from a module.

Note : You can only name-export first-class citizens that have a name.


  1. ``` js
  2. // mathConstants.js
  3. export const pi = 3.14;
  4. export const exp = 2.7;
  5. export const alpha = 0.35;

  6. // -------------

  7. // myFile.js
  8. import { pi, exp } from './mathConstants.js'; // Named import -- destructuring-like syntax
  9. console.log(pi) // 3.14
  10. console.log(exp) // 2.7

  11. // -------------

  12. // mySecondFile.js
  13. import * as constants from './mathConstants.js'; // Inject all exported values into constants variable
  14. console.log(constants.pi) // 3.14
  15. console.log(constants.exp) // 2.7
  16. ```

While named imports looks like destructuring, they have a different syntax and are not the same. They don't support default values nor deep destructuring.

Besides, you can do aliases but the syntax is different from the one used in destructuring:

  1. ``` js
  2. import { foo as bar } from 'myFile.js'; // foo is imported and injected into a new bar variable
  3. ```

Default import / export

Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is considered the "main" exported value since it will be the simplest to import. Ref: MDN

  1. ``` js
  2. // coolNumber.js
  3. const ultimateNumber = 42;
  4. export default ultimateNumber;

  5. // ------------

  6. // myFile.js
  7. import number from './coolNumber.js';
  8. // Default export, independently from its name, is automatically injected into number variable;
  9. console.log(number) // 42
  10. ```

Function exporting:

  1. ``` js
  2. // sum.js
  3. export default function sum(x, y) {
  4.   return x + y;
  5. }
  6. // -------------

  7. // myFile.js
  8. import sum from './sum.js';
  9. const result = sum(1, 2);
  10. console.log(result) // 3
  11. ```

External resources



### JavaScript *this*

this operator behaves differently than in other languages and is in most cases determined by how a function is called. (Ref: MDN).

This notion is having many subtleties and being quite hard, I highly suggest you to deep dive in the external resources below. Thus, I will provide what I personally have in mind to determine what this is equal to. I have learned this tip from this article written by Yehuda Katz.

  1. ``` js
  2. function myFunc() {
  3.   ...
  4. }

  5. // After each statement, you find the value of *this* in myFunc

  6. myFunc.call("myString", "hello") // "myString" -- first .call parameter value is injected into *this*

  7. // In non-strict-mode
  8. myFunc("hello") // window -- myFunc() is syntax sugar for myFunc.call(window, "hello")

  9. // In strict-mode
  10. myFunc("hello") // undefined -- myFunc() is syntax sugar for myFunc.call(undefined, "hello")
  11. ```

  1. ``` js
  2. var person = {
  3.   myFunc: function() { ... }
  4. }

  5. person.myFunc.call(person, "test") // person Object -- first call parameter is injected into *this*
  6. person.myFunc("test") // person Object -- person.myFunc() is syntax sugar for person.myFunc.call(person, "test")

  7. var myBoundFunc = person.myFunc.bind("hello") // Creates a new function in which we inject "hello" in *this* value
  8. person.myFunc("test") // person Object -- The bind method has no effect on the original method
  9. myBoundFunc("test") // "hello" -- myBoundFunc is person.myFunc with "hello" bound to *this*
  10. ```

External resources



Class


JavaScript is a prototype-based language (whereas Java is class-based language, for instance). ES6 has introduced JavaScript classes which are meant to be a syntactic sugar for prototype-based inheritance andnot a new class-based inheritance model (ref).

The word class is indeed error prone if you are familiar with classes in other languages. If you do, avoid assuming how JavaScript classes work on this basis and consider it an entirely different notion.

Since this document is not an attempt to teach you the language from the ground up, I will assume you know what prototypes are and how they behave. If you do not, see the external resources listed below the sample code.

Samples


Before ES6, prototype syntax:

  1. ``` js
  2. var Person = function(name, age) {
  3.   this.name = name;
  4.   this.age = age;
  5. }
  6. Person.prototype.stringSentence = function() {
  7.   return "Hello, my name is " + this.name + " and I'm " + this.age;
  8. }
  9. ```

With ES6 class syntax:

  1. ``` js
  2. class Person {
  3.   constructor(name, age) {
  4.     this.name = name;
  5.     this.age = age;
  6.   }

  7.   stringSentence() {
  8.     return `Hello, my name is ${this.name} and I am ${this.age}`;
  9.   }
  10. }

  11. const myPerson = new Person("Manu", 23);
  12. console.log(myPerson.age) // 23
  13. console.log(myPerson.stringSentence()) // "Hello, my name is Manu and I'm 23
  14. ```

External resources


For prototype understanding:


For classes understanding:


Extends and super keywords


The extends keyword is used in class declarations or class expressions to create a class which is a child of another class (Ref: MDN). The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones.

The super keyword is used to call functions on an object's parent, including its constructor.

- super keyword must be used before the this keyword is used in constructor
- Invoking super() calls the parent class constructor. If you want to pass some arguments in a class's constructor to its parent's constructor, you call it with super(arguments).
- If the parent class have a method (even static) called X, you can use super.X() to call it in a child class.

Sample Code


  1. ``` js
  2. class Polygon {
  3.   constructor(height, width) {
  4.     this.name = 'Polygon';
  5.     this.height = height;
  6.     this.width = width;
  7.   }

  8.   getHelloPhrase() {
  9.     return `Hi, I am a ${this.name}`;
  10.   }
  11. }

  12. class Square extends Polygon {
  13.   constructor(length) {
  14.     // Here, it calls the parent class' constructor with lengths
  15.     // provided for the Polygon's width and height
  16.     super(length, length);
  17.     // Note: In derived classes, super() must be called before you
  18.     // can use 'this'. Leaving this out will cause a reference error.
  19.     this.name = 'Square';
  20.     this.length = length;
  21.   }

  22.   getCustomHelloPhrase() {
  23.     const polygonPhrase = super.getHelloPhrase(); // accessing parent method with super.X() syntax
  24.     return `${polygonPhrase} with a length of ${this.length}`;
  25.   }

  26.   get area() {
  27.     return this.height * this.width;
  28.   }
  29. }

  30. const mySquare = new Square(10);
  31. console.log(mySquare.area) // 100
  32. console.log(mySquare.getHelloPhrase()) // 'Hi, I am a Square' -- Square inherits from Polygon and has access to its methods
  33. console.log(mySquare.getCustomHelloPhrase()) // 'Hi, I am a Square with a length of 10'
  34. ```

Note : If we had tried to use this before calling super() in Square class, a ReferenceError would have been raised:

  1. ``` js
  2. class Square extends Polygon {
  3.   constructor(length) {
  4.     this.height; // ReferenceError, super needs to be called first!

  5.     // Here, it calls the parent class' constructor with lengths
  6.     // provided for the Polygon's width and height
  7.     super(length, length);

  8.     // Note: In derived classes, super() must be called before you
  9.     // can use 'this'. Leaving this out will cause a reference error.
  10.     this.name = 'Square';
  11.   }
  12. }
  13. ```

External Resources



Async Await


In addition to Promises, there is a new syntax you might encounter to handle asynchronous code namedasync / await.

The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises. Async functions always return a Promise. (Ref: MDN)

Note : You must understand what promises are and how they work before trying to understand async / await since they rely on it.


Note 2: [await must be used in an async function](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9#f3f0), which means that you can't use await in the top level of our code since that is not inside an async function.


Sample code


  1. ``` js
  2. async function getGithubUser(username) { // async keyword allows usage of await in the function and means function returns a promise
  3.   const response = await fetch(`https://api.github.com/users/${username}`); // Execution is paused here until the Promise returned by fetch is resolved
  4.   return response.json();
  5. }

  6. getGithubUser('mbeaudru')
  7.   .then(user => console.log(user)) // logging user response - cannot use await syntax since this code isn't in async function
  8.   .catch(err => console.log(err)); // if an error is thrown in our async function, we will catch it here
  9. ```

Explanation with sample code


Async / Await is built on promises but they allow a more imperative style of code.

The async operator marks a function as asynchronous and will always return a Promise. You can use the await operator in an async function to pause execution on that line until the returned Promise from the expression either resolves or rejects.

  1. ``` js
  2. async function myFunc() {
  3.   // we can use await operator because this function is async
  4.   return "hello world";
  5. }

  6. myFunc().then(msg => console.log(msg)) // "hello world" -- myFunc's return value is turned into a promise because of async operator
  7. ```

When the return statement of an async function is reached, the Promise is fulfilled with the value returned. If an error is thrown inside an async function, the Promise state will turn to rejected. If no value is returned from an async function, a Promise is still returned and resolves with no value when execution of the async function is complete.

await operator is used to wait for a Promise to be fulfilled and can only be used inside an async function body. When encountered, the code execution is paused until the promise is fulfilled.

Note : fetch is a function that returns a Promise that allows to do an AJAX request


Let's see how we could fetch a github user with promises first:

  1. ``` js
  2. function getGithubUser(username) {
  3.   return fetch(`https://api.github.com/users/${username}`).then(response => response.json());
  4. }

  5. getGithubUser('mbeaudru')
  6.   .then(user => console.log(user))
  7.   .catch(err => console.log(err));
  8. ```

Here's the async / await equivalent:

  1. ``` js
  2. async function getGithubUser(username) { // promise + await keyword usage allowed
  3.   const response = await fetch(`https://api.github.com/users/${username}`); // Execution stops here until fetch promise is fulfilled
  4.   return response.json();
  5. }

  6. getGithubUser('mbeaudru')
  7.   .then(user => console.log(user))
  8.   .catch(err => console.log(err));
  9. ```

async / await syntax is particularly convenient when you need to chain promises that are interdependent.

For instance, if you need to get a token in order to be able to fetch a blog post on a database and then the author informations:

Note : await expressions needs to be wrapped in parentheses to call its resolved value's methods and properties on the same line.


  1. ``` js
  2. async function fetchPostById(postId) {
  3.   const token = (await fetch('token_url')).json().token;
  4.   const post = (await fetch(`/posts/${postId}?token=${token}`)).json();
  5.   const author = (await fetch(`/users/${post.authorId}`)).json();

  6.   post.author = author;
  7.   return post;
  8. }

  9. fetchPostById('gzIrzeo64')
  10.   .then(post => console.log(post))
  11.   .catch(err => console.log(err));
  12. ```

Error handling

Unless we add try / catch blocks around await expressions, uncaught exceptions – regardless of whether they were thrown in the body of your async function or while it’s suspended during await – will reject the promise returned by the async function. Using the throw statement in an async function is the same as returning a Promise that rejects. (Ref: PonyFoo).

Note : Promises behave the same!


With promises, here is how you would handle the error chain:

  1. ``` js
  2. function getUser() { // This promise will be rejected!
  3.   return new Promise((res, rej) => rej("User not found !"));
  4. }

  5. function getAvatarByUsername(userId) {
  6.   return getUser(userId).then(user => user.avatar);
  7. }

  8. function getUserAvatar(username) {
  9.   return getAvatarByUsername(username).then(avatar => ({ username, avatar }));
  10. }

  11. getUserAvatar('mbeaudru')
  12.   .then(res => console.log(res))
  13.   .catch(err => console.log(err)); // "User not found !"
  14. ```

The equivalent with async / await:

  1. ``` js
  2. async function getUser() { // The returned promise will be rejected!
  3.   throw "User not found !";
  4. }

  5. async function getAvatarByUsername(userId) => {
  6.   const user = await getUser(userId);
  7.   return user.avatar;
  8. }

  9. async function getUserAvatar(username) {
  10.   var avatar = await getAvatarByUsername(username);
  11.   return { username, avatar };
  12. }

  13. getUserAvatar('mbeaudru')
  14.   .then(res => console.log(res))
  15.   .catch(err => console.log(err)); // "User not found !"
  16. ```

External resources



Truthy / Falsy


In JavaScript, a truthy or falsy value is a value that is being casted into a boolean when evaluated in a boolean context. An example of boolean context would be the evaluation of an if condition:

Every value will be casted to true unless they are equal to:

- false
- 0
- "" (empty string)
- null
- undefined
- NaN

Here are examples of boolean context:

- if condition evaluation

  1. ``` js
  2. if (myVar) {}
  3. ```

myVar can be any first-class citizen (variable, function, boolean) but it will be casted into a boolean because it's evaluated in a boolean context.

- After logical NOT ! operator

This operator returns false if its single operand can be converted to true; otherwise, returns true.

  1. ``` js
  2. !0 // true -- 0 is falsy so it returns true
  3. !!0 // false -- 0 is falsy so !0 returns true so !(!0) returns false
  4. !!"" // false -- empty string is falsy so NOT (NOT false) equals false
  5. ```

- With the Boolean object constructor

  1. ``` js
  2. new Boolean(0) // false
  3. new Boolean(1) // true
  4. ```

- In a ternary evaluation

  1. ``` js
  2. myVar ? "truthy" : "falsy"
  3. ```

myVar is evaluated in a boolean context.

Be careful when comparing 2 values. The object values (that should be cast to true) is not being casted to Boolean but it forced to convert into a primitive value one using ToPrimitives specification. Internally, when an object is compared to Boolean value like[] == true, it does [].toString() == true so...

  1. ``` js
  2. let a = [] == true // a is false since [].toString() give "" back.
  3. let b = [1] == true // b is true since [1].toString() give "1" back.
  4. let c = [2] == true // c is false since [2].toString() give "2" back.
  5. ```

External resources



Anamorphisms and Catamorphisms


Anamorphisms


Anamorphisms are functions that map from some object to a more complex structure containing the type of the object. It is the process of unfolding a simple structure into a more complex one. Consider unfolding an integer to a list of integers. The integer is our initial object and the list of integers is the more complex structure.

Sample code

  1. ``` js
  2. function downToOne(n) {
  3.   const list = [];

  4.   for (let i = n; i > 0; --i) {
  5.     list.push(i);
  6.   }

  7.   return list;
  8. }

  9. downToOne(5)
  10.   //=> [ 5, 4, 3, 2, 1 ]
  11. ```

Catamorphisms


Catamorphisms are the opposite of Anamorphisms, in that they take objects of more complex structure and fold them into simpler structures. Take the