What is ES6 ?

Hossam Hilal
7 min readMar 1, 2020

--

What is ES6 ?

ES6 is also known as ECMAScript 6 and ECMAScript 2015.

Some people call it JavaScript 6.

ECMAScript(ES) is a standardised scripting language for JavaScript (JS). The current ES version supported in modern browsers is ES5. However, ES6 tackles a lot of the limitations of the core language, making it easier for devs to code.

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.

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.

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.

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

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

Arrow functions do not have their own this. They are not well suited for defining object methods.

Arrow functions are not hoisted. They must be defined before they are used.

Using const is safer than using var, because a function expression is always constant value.

You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:

const x = (x, y) => { return 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;
}
}

Now you can create objects using the Car class:

class Car {
constructor(brand) {
this.carname = brand;
}
}
mycar = new Car("Ford");

Default Parameter Values

ES6 allows function parameters to have default values.

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

Array.find()

The find() method returns the value of the first array element that passes a test function.

This example finds (returns the value of ) the first element that is larger than 18:

var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}

Note that the function takes 3 arguments:

  • The item value
  • The item index
  • The array itself

Array.findIndex()

The findIndex() method returns the index of the first array element that passes a test function.

This example finds the index of the first element that is larger than 18:

var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {
return value > 18;
}

Note that the function takes 3 arguments:

  • The item value
  • The item index
  • The array itself

Exponentiation Operator

The exponentiation operator (**) raises the first operand to the power of the second operand.

var x = 5;
var z = x ** 2; // result is 25

x ** y produces the same result as Math.pow(x,y):

var x = 5;
var z = Math.pow(x,2); // result is 25

New Number Methods

ES6 added 2 new methods to the Number object:

  • Number.isInteger()
  • Number.isSafeInteger()

The Number.isInteger() Method

The Number.isInteger() method returns true if the argument is an integer.

Number.isInteger(10);        // returns true
Number.isInteger(10.5); // returns false

The Number.isSafeInteger() Method

A safe integer is an integer that can be exactly represented as a double precision number.

The Number.isSafeInteger() method returns true if the argument is a safe integer.

Number.isSafeInteger(10);    // returns true
Number.isSafeInteger(12345678901234567890); // returns false

New Global Methods

ES6 also added 2 new global number methods:

  • isFinite()
  • isNaN()

- The isFinite() Method

The global isFinite() method returns false if the argument is Infinity or NaN.

Otherwise it returns true:

isFinite(10/0);       // returns false
isFinite(10/1); // returns true

- The isNaN() Method

The global isNaN() method returns true if the argument is NaN. Otherwise it returns false:

isNaN("Hello");       // returns true

Currently there are no browsers that support all the ES6 features, however we have a way to convert the ES6 code we write to the ES5 code that you are writing already. The method for doing this is called Transpiling.

There are currently two major compilers out there today, Babel and Traceur. Most modern projects that are written in ES6 will use one of these compilers to convert the ES6 code to ES5 as part of the build process.

The transpilation is performed as one of the first actions on the javascript file, so that future actions, such as minification or source map generation can still be performed.

Let’s take a look at the main differences between ES5 and ES6 syntax.

Fat Arrow Function (=>)

01 — Return Number function

// ES5  
function getNum() {
return 10;
}
// ES6
const getNum = () => 10;

02 — Return Array function

// ES5
function getArr() {
return [1, 2, 3];
}
// ES6
const getArr = () => [1, 2, 3];

03 — Return Object function

// ES5
function getObj() {
return { a: 1, b: 2, c: 3 };
}
// ES6
// Note the () to differentiate with actual code block
const getObj = () => ({ a: 1, b: 2, c: 3 });

04 — Return Number function with param

// ES5
function calcCircleArea(radius) {
return Math.PI * radius * radius;
}
// ES6
const calcCircleArea = (radius) => Math.PI * radius * radius;

05 — Return Number function with param and code block

// ES5
function calcCircleArea(radius) {
if (!radius) {
return null;
} else {
return Math.PI * radius * radius;
}
}
// ES6
const calcCircleArea = (radius) => {
if (!radius) {
return null;
} else {
return Math.PI * radius * radius;
}
};

Object Manipulation

01 — Extract object values

var obj1 = { a: 1, b: 2 };// ES5
var a = obj1.a;
var b = obj1.b;
// ES6
var { a, b } = obj1;

02 — Define object

var a = 1;
var b = 2;
// ES5
var obj1 = { a: a, b: b };
// ES6
var obj1 = { a, b };

03 — Merge objects with the spread operator (…)

var obj1 = { a: 1, b: 2 };
var obj2 = { c: 3, d: 4 };
// ES5
var obj3 = Object.assign(obj1, obj2);
// ES6
var obj3 = { ...obj1, ...obj2 };

Async Function (Callback vs. Promise)

// ES5 (callback)
function isEvenNumber(num, callback) {
if (num % 2 === 0) {
callback(true);
} else {
callback(false);
}
}
isEvenNumber(10, function(result) {
if (result) {
console.log('even number');
} else {
console.log('odd number');
}
});
// ES6
const isEvenNumber = (num) => {
return new Promise((resolve, reject) => {
if (num % 2 === 0) {
resolve(true);
} else {
reject(false);
}
});
};
isEvenNumber(10)
.then((result) => { console.log('even number'); })
.catch((error) => { console.log('odd number'); });

Promise also has some super useful methods like:

  • Promise.race → returns the first promise in the iterable to resolve
  • Promise.all → returns a promise when all the promises in the iterable have completed

Module Exports and Imports

01 — Export module

var testModule = { a: 1, b: 2 };// ES5
module.exports = testModule;
// ES6
export default testModule;
// ES6 (child modules)
export const a = 1;
export const b = 2;

02 — Import module

// ES5
var testModule = require(./testModule);
// ES6
import testModule from './testModule';
// ES6 (child modules)
import { a, b } from './testModule';

Template Literal (`)

const a = 1;
const b = 'b';
// ES5
const c = 'value of a is ' + a + ' and value of b is ' + b;
// ES6
const c = `value of a is ${a} and value of b is ${b}`;

Conclusion

This tutorial covers the main features of ES6, as you can see there are a number of improvements and changes that are going to drastically change how you write code.

I hope you found this intro to ES6 helpful, look out for more tutorials shortly, where we will be using ES6 in practice.

--

--

Hossam Hilal

Frontend Developer & WordPress Backend & UI / UX Designer .