logo

ES6 cheat sheet

Arrow function

An arrow function expression is a compact alternative to a traditional function expression, with some semantic changes.

Arrow function


        const sum = (a, b) => a + b

        console.log(sum(3, 4))  // prints 7
      

Default parameters

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Default parameters


        function print(a = 5) {
          console.log(a)
        }

        print() // prints 5
        print(22) // prints 22
      

let scope

The scope of a variable declared with let is just the enclosing block, not the whole enclosing function. They can be used only after initilization.

let scope


        let a = 3

        if (true) {
            let a = 5
            console.log(a) // prints 5
        }

        console.log(a) // prints 3      
      

const

The scope of a variable declared with let is just the enclosing block, not the whole enclosing function. They can be used only after initilization. Also, the const keyword creates a read-only reference to a value therefore the value cannot be re-assigned..

const


        // can be assigned only once:
        const a = 55;

        a = 44; // throws an error
      

Multiline string

Multi-line strings can be made using backticks(``).

Multiline string


        console.log(`
          This is a 
          multiline string
        `)
      

Template strings

Template strings allow variable names to be added inside a string using ${} - which is also known as string interpolation. It allows you to introduce any variables without having to concatenate them.

Template strings


        const name = 'Scott'
        const message = `Hello ${name}`

        console.log(message) // prints "Hello Scott"  
      

String includes()

The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false.

String includes()


        console.log('apple'.includes('pl')) // prints true
        console.log('apple'.includes('js')) // prints false
      

String startsWith()

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false.

String startsWith()


        console.log('apple'.startsWith('ap')) // prints true
        console.log('apple'.startsWith('bb')) // prints false
      

String repeat()

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together without spaces.

String repeat()


        console.log('ab'.repeat(3)) // prints "ababab"
      

Destructuring array

Array destructuring allows to unpack values from arrays into distinct variables.

Destructuring array


        const [a, b] = [3, 7];

        console.log(a); // 3
        console.log(b); // 7
      

Destructuring object

Object destructuring allows to unpack properties from objects, into distinct variables.

Destructuring object


        let obj = { 
          a: 55,
          b: 44
        };

        let { a, b } = obj;

        console.log(a); // 55
        console.log(b); // 44
      

Object property assignment

If the key and value (variable name) are same, then with ES6 it's possible to write them as only one of them instead of usign key:value.

Object property assignment


        const a = 2
        const b = 5

        const obj = { a, b }

        // Before es6:
        // obj = { a: a, b: b }

        console.log(obj) // prints { a: 2, b: 5 }   
      

Object function assignment

An arrow function or a regular function can be added as a value to an object key.

Object function assignment


        const obj = { 
          a: 5, 
          b: () => console.log('b'),
        }

        obj.b() // prints "b" 
      

Spread operator

A spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object.

Spread operator


        const a = [ 1, 2 ]
        const b = [ 3, 4 ]

        const c = [ ...a, ...b ]

        console.log(c) // [1, 2, 3, 4] 
      

Object.assign()

The Object.assign() method is used to copy the values and properties from one or more source objects to a target object.

Object.assign()


        const obj1 = { a: 1 };
        const obj2 = { b: 2 };

        const obj3 = Object.assign({}, obj1, obj2);

        console.log(obj3) // { a: 1, b: 2 };
      

Object.entries()

JavaScript Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.

Object.entries()


        const obj = {
          firstName: 'Scott',
          lastName: 'Adkins',
          age: 34,
          country: 'USA',
        };

        const entries = Object.entries(obj);  
        // returns an array of [key, value] pairs of the object passed.

        console.log(entries);  
        /* prints
            [
              ['firstName', 'Scott'], 
              ['lastName', 'Adkins'], 
              ['age', 34], 
              ['country', 'USA']
            ];
        */ 
      

Spread operator in objects

The spread operator allows us to copy all properties from an existing object into another object, and replacing / adding any key:value updated or added.

Spread operator in objects


        const a = {
          firstName: "Hello",
          lastName: "World",
        }

        const b = {
          ...a,
          lastName: "Ocean",
          canSing: true,	
        }

        console.log(a) // {firstName: "Hello", lastName: "World"}

        console.log(b) // {firstName: "Hello", lastName: "Ocean", canSing: true}

        // great for modifying objects without side effects/affecting the original
      

Destructuring Nested Objects

ES6 allows us to destructure nested objects, as required.

Destructuring Nested Objects


        const Person = {
          name: "John Smilga",
          address: {
            country: "Westeros",
            state: "The Crownlands",
            city: "Kings Landing",
            pinCode: "500014",
          },
        };

        const { address : { state, pinCode }, name } = Person;

        console.log(name, state, pinCode) // John Smilga The Crownlands 500014
        console.log(city) // ReferenceError
      

Exponent operator

The exponent operator returns the result of raising the first operand to the power of the second operand.

Exponent operator


        const byte = 2 ** 8

        // Same as: Math.pow(2, 8)
      

Promises with finally

A promise represents the completion of an asynchronous operation. It returns a single value based on the operation being rejected or resolved. Once a Promise gets fulfilled or rejected, it becomes immutable.

Promises with finally


        promise
          .then((result) => { ··· })
          .catch((error) => { ··· })
          .finally(() => { // logic independent of success/error })

        // The handler is called when the promise is fulfilled or rejected.