ECMAScript is a standardised scripting language specification defining the core features and syntax of a scripting language. JavaScript is a widely used implementation of ECMAScript, known for its use in web development, incorporating the ECMAScript rules while adding web-specific features.

ECMAScript 6, also known as ES6 or ECMAScript 2015, brought significant enhancements to JavaScript. These improvements made JavaScript code more readable, maintainable, and efficient. In this article, we will explore several ES6 features with practical examples to help you leverage the power of modern JavaScript.

1. Let and Const

ES6 introduced two new variable declaration keywords, let and const, in addition to the existing var. let allows for block-scoped variables, and const is used for constants whose values should not be reassigned.

// Using let

let counter = 0;

if (true) {

  let counter = 1;

  console.log(counter); // 1

}

console.log(counter); // 0

// Using const

const PI = 3.14159;

// PI = 3.14; // Error: Assignment to constant variable

2. Arrow Functions

Arrow functions provide a more concise syntax for defining functions and capture this value from the surrounding context.

  • Use the arrow (=>) between the function parameters and the function body.
  • If the function takes a single parameter, you can omit the parentheses around the parameter.
  • If the function body is a single expression, you can omit the curly braces {} and the return keyword.
  • If there are no parameters, or multiple parameters, use parentheses for clarity.

// ES5 function

function add(x, y) {

  return x + y;

}

// ES6 arrow function

const add = (x, y) => x + y;

// Arrow function with implicit return

const square = (x) => x * x;

// Arrow function with no arguments

const greet = () => ‘Hello, world!’;

3. Template Literals

Template literals allow you to create multi-line strings and embed expressions within them using ${}.

const name = ‘Alice’;

const greeting = `Hello, ${name}! Welcome to our website.`;

console.log(greeting);

Expected output:

Hello, Alice! Welcome to our website.

Here, name is a variable that holds the string “Alice,” while greeting is a string that combines the value of name with additional text to create a welcoming message.

4. Destructuring

Destructuring enables you to extract values from objects and arrays into separate variables.

// Object destructuring

const person = { name: ‘John’, age: 30 };

const { name, age } = person;

console.log(name, age);

// Array destructuring

const numbers = [1, 2, 3];

const [first, second, third] = numbers;

console.log(first second, third);

Expected output:

John 30

1 2 3

In the first part, the line const { name, age } = person; performs object destructuring. It declares two variables, name and age, and assigns them the values extracted from the person object. 

After this line executes:

  • name will have the value ‘John’, which is the value of person.name.
  • age will have the value 30, which is the value of person.age.

In the second part, the numbers array contains three values: 1, 2, and 3.

The array destructuring assigns these values to the variables first, second, and third respectively.

5. Spread and Rest Operators

The spread operator (…) can be used to spread elements of an array or object into another array or object, while the rest operator collects multiple function arguments into an array.

// Spread operator

const numbers = [1, 2, 3];

const newNumbers = […numbers, 4, 5];

// Rest operator

function sum(…args) {

  return args.reduce((total, num) => total + num, 0);

}

In the first part, const newNumbers = […numbers, 4, 5]; uses the spread operator to create a new array newNumbers that includes all the elements from the numbers array (1, 2, 3), as well as the numbers 4 and 5.

In the second part, the sum function uses the rest parameter …args to accept any number of arguments and store them in an array called args.

The function then uses the reduce method to calculate the sum of all the values in the args array.

This allows you to call the sum function with any number of arguments, and it will calculate their sum. For example, sum(1, 2, 3) will return 6, and sum(1, 2, 3, 4, 5) will return 15.

6. For… of

The for…of loop provides an easy and concise way to iterate over iterable objects, including arrays, strings, maps, sets, and more. It simplifies the process of looping through elements compared to traditional for and forEach loops.

const cities = [‘tokyo’, ‘mumbai’, ‘vancouver’];

for (const city of cities) {

  console.log(city);

}

Expected output:

tokyo

mumbai

vancouver

7. Classes

ES6 introduced a class syntax for creating object constructors and prototypes, making it more similar to object-oriented languages. 

class Person {

  constructor(name, age) {

    this.name = name;

    this.age = age;

  }

  greet() {

    return `Hello, my name is ${this.name} and I’m ${this.age} years old.`;

  }

}

const alice = new Person(‘Alice’, 25);

console.log(alice.greet());

In the code, a class named Person is defined with a constructor and a greet method. Here’s what happens when you execute the code:

  • The Person class is defined with a constructor that takes two parameters, name and age. Inside the constructor, the values of name and age are assigned to the respective properties of the newly created object.
  • An instance of the Person class is created with the name “Alice” and age 25 using the new keyword: const alice = new Person(‘Alice’, 25);. This creates a new object based on the Person class, and the name property is set to “Alice,” and the age property is set to 25 for this instance.
  • The greet method of the alice object is called using alice.greet(). This method returns a string that includes the name and age properties of the alice object, providing a greeting message.

Expected output:

Hello, my name is Alice and I’m 25 years old.

8. Modules

ES6 modules allow you to split your code into multiple files, making it easier to manage and reuse code across different parts of your application.

// math.js (exporting)

export const add = (x, y) => x + y;

// app.js (importing)

import { add } from ‘./math.js’;

console.log(add(2, 3)); // 5

In the math.js module, the add function is defined and exported as a named export using the export statement.

In the app.js module, the add function is imported using the import statement. This allows you to use the add function in the app.js module.

The console.log statement in app.js calls the add function with the arguments 2 and 3. This results in the function adding these two numbers together.

The result of the addition, which is 5, is then logged to the console.

Conclusion

These ES6 features represent just a fraction of the enhancements that ECMAScript 2015 brought to JavaScript. By incorporating these features into your code, you can write more readable, maintainable, and efficient JavaScript applications. ES6 has become the foundation for modern JavaScript development, and understanding these features is essential for any JavaScript developer.