Progressive Full Stack Application Development with Live Projects

JavaScript

JavaScript ES6 Features + Code Examples

  • JavaScript ES6 Features Explained with Code Examples

JavaScript was initially designed as a language for writing interactive web applications. Hence it needed to be small and easy to implement. ECMAScript 6 (or ES6), also known as ECMAScript 2015, was a major update to the JavaScript language that introduced a variety of new features for making JavaScript development easier and more powerful.

In this lesson we will discuss about some of the most notable ES6 features with examples.

1. Let and Const


let and const were added to declare variables with block scope.

  • let allows us to declare variables that are scoped to the block in which they are defined.
  • const declares variables that cannot be reassigned (though the content of objects and arrays can still be modified).
// Using let
if (true) {
    let x = 10;
    console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined

// Using const
const y = 20;
console.log(y); // 20
y = 30; // TypeError: Assignment to constant variable

Note: Variables declared with the var keyword can NOT have block scope even if it is declared inside a block. Such variables can be accessed outside the defining block.

2. Arrow Functions


Arrow functions provide a shorter syntax for writing functions and have lexical this binding.

// Regular function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

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

Arrow function expressions should only be used for non-method functions because they do not have their own this or bindings to arguments, or super. Learn more about Arrow Functions on Mozilla Docs.

3. Template Literals


Template literals allow for easier string interpolation and multi-line strings. Without template literals, when we want to combine output from expressions with strings, we need to concatenate them using the addition operator +.

With template literals, we can avoid the concatenation operator and improve the readability of our code by using placeholders of the form ${expression} to perform substitutions for embedded expressions.

  • Template literals are delimited with backtick (`) characters instead of single or double quotes
  • Template literals are also called template strings
const name = "John";
const age = 30;

// Template literal with interpolation
const greeting = `Hi, my name is ${name} and I am ${age} years old.`;

console.log(greeting); // Hi, my name is John and I am 30 years old.

4. Destructuring Assignment


Destructuring allows us to unpack values from arrays or properties from objects into distinct variables.

// Array destructuring
const numbers = [1, 2, 3];
const [one, two, three] = numbers;

console.log(one); // 1
console.log(two); // 2
console.log(three); // 3

// Object destructuring
const person = { name: 'Alice', age: 25 };
const { name, age } = person;

console.log(name); // Alice
console.log(age); // 25

5. Default Parameters


Functions can have default values for parameters.

function greet(name = "Guest") {
    return `Hello, ${name}!`;
}

console.log(greet()); // Hello, Guest!
console.log(greet("Alice")); // Hello, Alice!

6. Rest and Spread Operators


  • Rest parameters collect all arguments into an array.
  • Spread syntax spreads elements of an array or object into separate items.
// Rest parameters
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

// Spread syntax
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

console.log(combined); // [1, 2, 3, 4, 5, 6]

7. Classes


ES6 introduces a class syntax for creating objects and handling inheritance.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        return `Hello, my name is ${this.name}.`;
    }
}

const alice = new Person('Alice', 25);
console.log(alice.greet()); // Hello, my name is Alice.

8. Modules


ES6 modules allow you to export and import code between different files.

// file: math.js
export const pi = 3.14;
export function add(x, y) {
    return x + y;
}

// file: main.js
import { pi, add } from './math.js';

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

9. Promises


Promises provide a way to work with asynchronous operations more effectively than traditional callbacks.

const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve("Data received"), 1000);
    });
};

fetchData().then(data => console.log(data)); // Data received

10. Enhanced Object Literals


ES6 makes it easier to define methods and properties in object literals.

const name = 'John';
const person = {
    name,
    greet() {
        return `Hello, ${this.name}!`;
    }
};

console.log(person.greet()); // Hello, John!

These ES6 Features features make JavaScript more powerful and expressive, allowing for cleaner, more maintainable code.