Skip to main content

Command Palette

Search for a command to run...

JavaScript - ES6

Updated
JavaScript - ES6

let, const

  • before 2015, var was used to declare a variable

  • after 2015, let and const were introduced

Arrow Function

// original ways to declare function
function add() {}

var add = function () {};

// arrow function
var add = () => {
    return 1;
};

var add = (x) => 1;

Ternary Operator

// condition ? true : false
console.log(true ? "true" : "false"); // true

Destructuring

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and arrays.

// Array Destructuring
let [value1, value2] = [1, "new"];
console.log(value1); // 1
console.log(value2); // "new"

let arr = ["value1", "value2", "value3"];
let [a, b, c, d] = arr;
console.log(a); // "value1"
console.log(b); // "value2"
console.log(c); // "value3"
console.log(d); // undefined

[a, b, c, d = 4] = arr; // set default value
console.log(d); // 4

// used to swap values
[a1, a2] = [a2, a1]
// Object Destructuring
let user = {
    name: "John",
    age: 30,
};

let { name, age, birth="today" } = user;
console.log("name =>", name); // "John"
console.log("age =>", age); // 30 
console.log("birth =>", birth); // "today"


// Destructuring Assignment
let { name: newName, age: newAge } = user;
console.log("newName =>", newName); // "John"
console.log("newAge =>", newAge); // 30

Property Shorthand

if the key and value are the same, we can use the shorthand

const name = "John";
const age = 30;

const obj = {
    name, // if name: name, we can use name only
    age: age,
};

const obj2 = { name, age }; // RHS is still the object

Spread Operator

Most frequently used with destructuring in ES6

The Spread operator is used to split up array elements or object properties

let arr = [1, 2, 3, 4, 5];
console.log(arr); // [1, 2, 3, 4, 5]
console.log(...arr); // 1 2 3 4 5 - removing [] and spread out the elements

let newArr = [...arr, 6, 7, 8];
console.log(newArr); // [1, 2, 3, 4, 5, 6, 7, 8]

let person = {
    name: "John",
    age: 30,
};

let person1 = { ...person }; // removing {} and spread out the key-value pairs
console.log(person1); // { name: 'John', age: 30 }

Rest Parameter

The rest parameter is used to represent an indefinite number of arguments as an array

The rest parameter must be the last parameter in a function

function exampleFunc(a, b, c, ...args) {
    console.log(a, b, c); // 1 2 3
    console.log(...args); // 4 5 6 7 8 9 10
    console.log(args); // [4, 5, 6, 7, 8, 9, 10]
}

exampleFunc(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 1 2 3

Template Literals

Template literals are string literals allowing embedded expressions

Template literals are enclosed by the back-tick (` ) (grave accent) character instead of double or single quotes

let name1 = "Siwon";
let age1 = 22;

console.log(`Hello, my name is ${name1}. I am ${age1} years old.`);

// supporting multi-line
console.log(`
    Hello, 
        my name is ${name1}.
        I am ${age1} years old.
`);

Named export vs. Default export

// default export
// Under name.js
const Name = () => {
}

export default Name

// Under other files - we can use any names to import:
import newName from "name.js"
import NameFromOtherModule from "name.js"
// named export
// we can export multiple functions/classes in one file
// Under name.js
export const Name1 = () => {
}

export const Name2 = () => {
}

// Under other files
import {Name1, Name2} from "name.js"
import {newName} from "name.js" // x

// use alias to import in different names
import {Name1 as newName, Name2} from "name.js"

// use * to import like default export
import * as NameModule from "name.js"

console.log(NameModule.Name1)

Function as First-Class Object

a function is very flexible in JS

// 1. Assign function to variable
const sayHello = function () {
    console.log("Hello");
};
// 2. Pass function as parameter
// callback function = function as parameter: sayHello
// higher-order function = function that takes function as parameter: callFunction
function callFunction(func) {
    func();
}

callFunction(sayHello); // Hello
// 3. Return function from function
function createAdder(num) {
    return function (x) {
        return x + num;
    };
}

const addFive = createAdder(5);
console.log(addFive(10)); // 15
// 4. Function as property of object
const person = {
    name: "John",
    age: 31,
    isMarrid: true,
    sayHello: () => {
        console.log(`Hello, my name is ${this.name}`); // this.name = undefined
    },
    sayHello1: function () {
        console.log(`Hello, my name is ${this.name}`);
    },
};

person.sayHello(); // Hello, my name is undefined: arrow function does not have 'this' keyword
person.sayHello1(); // Hello, my name is John
// 5. Function as property of array
const myArr = [
    function (a, b) {
        return a + b;
    },
    function (a, b) {
        return a - b;
    },
];

console.log(myArr[0](1, 2)); // 3
console.log(myArr[1](1, 2)); // -1

console.log("====================================");

function multiplyBy(num) {
    return function (x) {
        return x * num;
    }
}

function add(x, y) {
    return x + y;
}

const multiplyByTwo = multiplyBy(2); // efficient way by reusing multiplyBy function
const multiplyByThree = multiplyBy(3);

console.log(multiplyByTwo(5)); // 10
console.log(multiplyByThree(5)); // 15

const result = add(multiplyByTwo(5), multiplyByThree(5));
console.log(`Result: ${result}`); // 25

Map & Set

Even though there are many features we can utilize in JS such as an object, array, etc, it is still hard to reflect the real world.

Thus, map and set data structures have been introduced to JS

Map

  • key-value pair

  • any data type of key can be used

  • map saves the insertion order of the keys

  • Methods:

    • new Map() – create map

    • map.set(key, value) – store value by using key

    • map.get(key) – return the value of the key (if the key doesn't exist, return undefined)

    • map.has(key) – if the key exists, return true, otherwise return false

    • map.delete(key) – delete the value of key

    • map.clear() – clear all the data in the map

    • map.size() – return the size of the map

// map is for dealing with the massive data
// so, the iteration is important
// Iteration Methods: keys(), values(), entries()
const myMap = new Map();
myMap.set("one", 1);
myMap.set("two", 2);
myMap.set("three", 3);

console.log(myMap.keys()); // MapIterator {"one", "two", "three"}

// for of: the way to iterate through the map
for (const key of myMap.keys()) {
    console.log(key);
}

console.log(myMap.values()); // MapIterator {1, 2, 3}

for (const value of myMap.values()) {
    console.log(value);
}

console.log(myMap.entries()); // MapIterator {"one" => 1, "two" => 2, "three" => 3}

for (const entry of myMap.entries()) {
    console.log(entry);
}

console.log(myMap.size()); // 3
console.log(myMap.has("one")); // true

Set

  • a collection of "unique" values

  • only values are stored, not keys

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // duplicate value is ignored

console.log(mySet.size); // 3
console.log(mySet.has(1)); // true

// Iteration
for (const value of mySet.values()) {
    console.log(value);
}