ES6 Features

JavaScript

Sat Jan 20 2018

Arrows

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

The arrow function definition consists of a parameter list ( … ), followed by the => marker and a function body.

// Implementation with arrow function
(param1, param2, …, paramN) => { statements } 
const addition = (a, b) => a + b;
// equivalent to: => { return expression; } 
(parm1, aparam2, …, paramN) => expression
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
const add5 = a => 5 + a;
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of function to return an object literal expression
params => ({foo: bar}) 
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements } 
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { 
statements } 

Default Function Parameters

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed. In JavaScript, function parameters default to undefined. However, it’s often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined.

const getFinalPrice = (price, tax = 0.7) => price + price * tax;
getFinalPrice(500); // 850

Rest & Spread

A function’s last parameter can be prefixed with … which will cause all remaining (user supplied) arguments to be placed within “standard” javascript array. Only the last parameter can be a “rest parameter”.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a); 
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs); 
}

myFun("one", "two", "three", "four", "five", "six");

… operator is referred to as spread or rest operator, depending on how and where it is used. When used with any iterable, it acts as to “spread” it into individual elements

function foo(x, y, z) {
    console.log(x, y, z);
}

let arr = [1, 2, 3];
foo(...arr); // 1 2 3

Spread is also great for shaping a new object from other object(s)

const defaults = {avatar: 'placeholder.jpg', active: false}
const userData = {username: 'foo', avatar: 'bar.jpg'}

console.log({created: '2017-12-31', ...defaults, ...userData})

// {created: "2017-12-31", avatar: "bar.jpg", active: false, username: "foo"}

You can also use it to merge arrays e.g.

const arr1 = [1, 2, 3];
const arr2 = [7, 8, 9];
console.log([...arr1, 4, 5, 6, ...arr2]) // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

var a, b, rest;

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: [30,40,50]
var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true
({ a, b } = { a: 10, b: 20 });

console.log(a); // 10

console.log(b); // 20

Class

ES6 introduces new class syntax. One thing to note here is that ES6 class is not a new object-oriented inheritance model. They just serve as a syntactical sugar over JavaScript’s existing prototype-based inheritance

The class declaration creates a new class with a given name using prototype-based inheritance.

class Person {

    constructor(name) {
        this.name = name;
        console.log('A person named "' + name + '" is born');
    }

    sayHello() {
        console.log(this.name + ' says hello');
    }
}
console.log(new Person('joe').sayHello);

extends and super in classes

class Car {
    constructor() {
        console.log("Creating a new car");
    }
}

class Porsche extends Car {
    constructor() {
        super();
        console.log("Creating Porsche");
    }
}

let c = new Porsche();
// Creating a new car
// Creating Porsche

Enhanced object literals

ES6 allows declaring object literals by providing shorthand syntax for initializing properties from variables and defining function methods. It also enables the ability to have computed property keys in an object literal definition.

Instead of { foo: foo }, you can just do { foo } – known as a property value shorthand

Template strings

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. Template literals are enclosed by the back-tick () character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).

var name = 'John';
console.log(`Hello ${name}`);

Template literals allow interpolation like This is ${rating} where rating is a variable You can use any valid JavaScript expressions in the interpolation, such as ${2 * 3} or ${foo()} The result of fn becomes the value of the template literal Template literals are almost strictly better than strings wrapped in single or double quotes

Source https://developer.mozilla.org/en-US/docs/Web/JavaScript

Loading...
Deepak Mishra

Deepak Mishra #JavaScript, #Node, #React #Angular, #jQuery, #HTML5, #CSS blog

  • www.deepakmihsra.com