ES6 Syntax and Feature Overview

Many improvements to JavaScript were made in ECMAScript 2015, commonly known as ES6 Syntax. Here are examples of some of the most popular features and syntax changes, along with some comparisons to ES5.

Variables and constant feature comparison

KeywordScopeHoistingCan Be ReassignedCan Be Redeclared
varFunction scopeYesYesYes
letBlock scopeNoYesNo
constBlock scopeNoNoNo

Variable declaration in ES6 Syntax

The let keyword was introduced in ES6 to enable block-scoped variables that cannot be hoisted or redeclared.

ES5:

var x = 0

ES6:

let x = 0

MDN Reference: let

Constant declaration in ES6 Syntax

The const keyword was add in ES6, and it cannot be redeclare or reassign. Although it is not immutable.

ES6:

const CONST_IDENTIFIER = 0  // constants are uppercase by convention

MDN Reference: const

Arrow functions in ES6 Syntax

The arrow function expression syntax is a more close way of expressing a function. Arrow functions have no this, no prototypes, can’t be use as constructors, and shouldn’t be utilize as object methods.

ES5:

function func(a, b, c) {}            // function declaration
var func = function (a, b, c) {} // function expression

ES6:

let func = (a) => {}         // parentheses optional with one parameter
let func = (a, b, c) => {} // parentheses required with multiple parameters

MDN Reference: Arrow functions

Template literals in ES6 Syntax

Concatenation

Expressions can be embed in template literal strings.

ES5:

var str = 'Release date: ' + date

ES6:

let str = `Release Date: ${date}`

MDN Reference: Expression interpolation

Multi-line strings

A JavaScript string can span many lines without the requirement for concatenation when using a template literal syntax.

ES5:

var str = 'This text ' + 'is on ' + 'multiple lines'

ES6:

let str = `This text
            is on
            multiple lines`

MDN Reference: Multi-line strings

Implicit returns

When employing arrow functions without a block body, the return keyword is inferred and can be skipped.

ES5:

function func(a, b, c) {
  return a + b + c
}

ES6:

let func = (a, b, c) => a + b + c      // curly brackets must be omitted

MDN Reference: Function body

Key and property shorthand

For assigning properties to variables with the same name, ES6 offers a simpler syntax.

ES5:

var obj = {
  a: a,
  b: b,
}

ES6:

let obj = {
  a,
  b,
}

MDN Reference: Property definitions

Method definition shorthand

When assigning methods to an object, the function keyword might be skipped.

ES5:

var obj = {
  a: function (c, d) {},
  b: function (e, f) {},
}

ES6:

let obj = {
  a(c, d) {},
  b(e, f) {},
}
obj.a() // call method a

MDN Reference: Method definitions

Destructuring in ES6 Syntax

To assign an object’s properties to its own variable, use curly brackets.

var obj = {a: 1, b: 2, c: 3}

ES5:

var a = obj.a
var b = obj.b
var c = obj.c

ES6:

let {a, b, c} = obj

MDN Reference: Object initializer

Array iteration in ES6 Syntax

Iteration across arrays and other iterable objects now has a more streamlined syntax.

var arr = ['a', 'b', 'c']

ES5:

for (var i = 0; i < arr.length; i++) {
  console.log(arr[i])
}

ES6:

for (let i of arr) {
  console.log(i)
}

MDN Reference: for…of

Default parameters

Functions can be started with default parameters, which are only utilized if the function is not called with an argument.

ES5:

var func = function (a, b) {
  b = b === undefined ? 2 : b
  return a + b
}

ES6:

let func = (a, b = 2) => {
  return a + b
}
func(10)     // returns 12
func(10, 5) // returns 15

MDN Reference: Default paramters

Spread syntax

The spread syntax can be used to expandan array.

ES6:

let arr1 = [1, 2, 3]
let arr2 = ['a', 'b', 'c']
let arr3 = [...arr1, ...arr2]

console.log(arr3) // [1, 2, 3, "a", "b", "c"]

The spread syntax can be used for function arguments.

ES6:

let arr1 = [1, 2, 3]
let func = (a, b, c) => a + b + c

console.log(func(...arr1)) // 6

MDN Reference: Spread syntax

Classes and constructor functions

On top of the prototype-based function Object() { [native code] } function, ES6 adds the class syntax.

ES5:

function Func(a, b) {
  this.a = a
  this.b = b
}

Func.prototype.getSum = function () {
  return this.a + this.b
}

var x = new Func(3, 4)

ES6:

class Func {
  constructor(a, b) {
    this.a = a
    this.b = b
  }

  getSum() {
    return this.a + this.b
  }
}

let x = new Func(3, 4)
x.getSum() // returns 7

MDN Reference: Classes

Inheritance

The extends the keyword creates a subclass.

ES5:

function Inheritance(a, b, c) {
  Func.call(this, a, b)

  this.c = c
}

Inheritance.prototype = Object.create(Func.prototype)
Inheritance.prototype.getProduct = function () {
  return this.a * this.b * this.c
}

var y = new Inheritance(3, 4, 5)

ES6:

class Inheritance extends Func {
  constructor(a, b, c) {
    super(a, b)

    this.c = c
  }

  getProduct() {
    return this.a * this.b * this.c
  }
}

let y = new Inheritance(3, 4, 5)
y.getProduct() // 60

MDN Reference: Subclassing with extends

Modules – export and import

Modules can be created to export and import code between files.

index.html

<script src="export.js"></script>
<script type="module" src="import.js"></script>

export.js

let func = (a) => a + a
let obj = {}
let x = 0

export {func, obj, x}

import.js

import {func, obj, x} from './export.js'

console.log(func(3), obj, x)

MDN Reference: export
MDN Reference: import

Promises and Callbacks

An asynchronous function’s completion is represented via promises. As an alternative to chaining functions, they can be utilized.

ES5 callback:

function doSecond() {
  console.log('Do second.')
}

function doFirst(callback) {
  setTimeout(function () {
    console.log('Do first.')

    callback()
  }, 500)
}

doFirst(doSecond)

ES6 promise:

let doSecond = () => {
  console.log('Do second.')
}

let doFirst = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('Do first.')

    resolve()
  }, 500)
})

doFirst.then(doSecond)

An example utilizing XMLHttpRequest is provided below. or demonstration reasons only (Fetch API would be the proper modern API to use).

ES5 callback:

function makeRequest(method, url, callback) {
  var request = new XMLHttpRequest()

  request.open(method, url)
  request.onload = function () {
    callback(null, request.response)
  }
  request.onerror = function () {
    callback(request.response)
  }
  request.send()
}

makeRequest('GET', 'https://url.json', function (err, data) {
  if (err) {
    throw new Error(err)
  } else {
    console.log(data)
  }
})

ES6 promise:

function makeRequest(method, url) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()

    request.open(method, url)
    request.onload = resolve
    request.onerror = reject
    request.send()
  })
}

makeRequest('GET', 'https://url.json')
  .then((event) => {
    console.log(event.target.response)
  })
  .catch((err) => {
    throw new Error(err)
  })

MDN Reference: Using_promises

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]

Leave a Comment