ES6 JavaScript

 ES6

Some people call it JavaScript 6.

This chapter will introduce some of the new features in ES6.

JavaScript let
JavaScript const
JavaScript Arrow Functions
JavaScript Classes
Default parameter values
Array.find()
Array.findIndex()
Exponentiation (**) (EcmaScript 2016)

JavaScript let

The let statement allows you to declare a variable with block scope.

Example
var x = 10;
// Here x is 10
{
  let x = 2;
  // Here x is 2
}
// Here x is 10


JavaScript const

The const statement allows you to declare a constant (a JavaScript variable with a constant value).

Constants are similar to let variables, except that the value cannot be changed.

Example
var x = 10;
// Here x is 10
{
  const x = 2;
  // Here x is 2
}
// Here x is 10



Arrow Functions

Arrow functions allows a short syntax for writing function expressions.

You don't need the function keyword, the return keyword, and the curly brackets.

Example
// ES5
var x = function(x, y) {
   return x * y;
}

// ES6
const x = (x, y) => x * y;


Classes

ES6 introduced classes.

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.

Use the keyword class to create a class, and always add a constructor method.

The constructor method is called each time the class object is initialized.

Example
A simple class definition for a class named "Car":

class Car {
  constructor(brand) {
    this.carname = brand;
  }
}


Default Parameter Values

ES6 allows function parameters to have default values.

Example
function myFunction(x, y = 10) {
  // y is 10 if not passed or undefined
  return x + y;
}
myFunction(5); // will return 15

Comments

Popular Posts