JavaScript ES6+ Features

ECMAScript 2015, also known as ES6, was a major update to JavaScript that introduced many new features to make the language more powerful and easier to write. Here are some of the most important ones.

1. let & const

let and const introduced block-scoped variables, which are confined to the {} block they are defined in. This is a significant improvement over var, which is function-scoped.

if (true) {
    var x = "I am function-scoped";
    let y = "I am block-scoped";
    const z = "I am also block-scoped";
}

console.log(x); // "I am function-scoped"
// console.log(y); // ReferenceError: y is not defined
        
Output will appear here...

2. Template Literals

Template literals provide an easy way to create multi-line strings and perform string interpolation (embedding expressions in strings).

let name = "Ragini";
let multiLineString = `
This is a
multi-line string.
`;
let greeting = `Hello, ${name}! The year is ${new Date().getFullYear()}.`;

console.log(greeting);
        
Output will appear here...

3. Arrow Functions

Arrow functions offer a more concise syntax for writing functions. A key difference is that they do not have their own this context; they inherit it from the parent scope (lexical scoping).

// Traditional function
const add_es5 = function(a, b) {
    return a + b;
};

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

console.log(add(5, 3)); // 8
        
Output will appear here...

4. Destructuring

Destructuring makes it easy to unpack values from arrays or properties from objects into distinct variables.

Object Destructuring

const person = { name: "Ragini", age: 25, city: "Delhi" };
const { name, age } = person;

console.log(name); // "Ragini"
console.log(age);  // 25
        
Output will appear here...

Array Destructuring

const fruits = ["Apple", "Banana", "Mango"];
const [first, second] = fruits;

console.log(first);  // "Apple"
console.log(second); // "Banana"
        
Output will appear here...

5. Default Parameters

You can now provide default values for function parameters, making functions more robust.

function greet(name = "Guest") {
    console.log(`Hello, ${name}`);
}

greet();        // Hello, Guest
greet("Ragini"); // Hello, Ragini
        
Output will appear here...

6. Spread & Rest Operators

The three dots (...) can be used for both spreading elements and gathering them.

Spread Operator

Expands an iterable (like an array or object) into individual elements.

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
console.log(arr2);

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
console.log(obj2);
        
Output will appear here...

Rest Operator

Collects multiple elements and "condenses" them into a single array. It's often used in function parameters.

function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // 15
        
Output will appear here...

7. Modules

ES6 introduced a native module system, allowing you to split your code into separate files and import/export functionalities as needed. This helps in organizing large codebases.

// In file math.js
// export const PI = 3.14;

// In file main.js
// import { PI } from './math.js';
// console.log(PI);
        

Comparison Table: ES5 vs ES6 Features

Feature ES5 ES6
Variable Scope var (Function-scoped) let, const (Block-scoped)
Functions function() {} Arrow functions () => {}
Strings Concatenation with + Template Literals with `${}`
Destructuring Manual assignment const {a} = obj
Modules Third-party libraries (e.g., CommonJS) Native import/export
Spread/Rest .apply(), manual loops ... operator
Best Practice: Embrace ES6+ features like const/let, arrow functions, and destructuring for cleaner, more modern, and less error-prone JavaScript code.

Practice Questions

Test your understanding of JavaScript ES6 Features.

Easy

Q1: Convert to an arrow function.

  • Assume you have a standard function: function multiply(a, b) { return a * b; }.
  • Rewrite this function as an ES6 arrow function named multiply.
  • Make it a single-line implicit return if possible.
Easy

Q2: Use template literals for string interpolation.

  • Declare two variables: firstName = "John" and lastName = "Doe".
  • Create a new variable named greeting using template literals (backticks).
  • Embed the variables to form the string "Hello, John Doe!".
  • Log the greeting to the console.
Medium

Q3: Extract properties using object destructuring.

  • Given an object: const book = { title: "1984", author: "George Orwell", year: 1949 };
  • Use object destructuring to extract the title and author properties into distinct variables.
  • Log both variables to the console.
Medium

Q4: Combine arrays using the spread operator.

  • Assume you have two arrays: const fruits1 = ["Apple", "Banana"]; and const fruits2 = ["Cherry", "Date"];.
  • Create a new array named allFruits.
  • Use the spread operator (...) to combine the elements of both arrays into allFruits.
Hard

Q5: Use the rest operator in function parameters.

  • Write a function named calculateTotal.
  • The first parameter should be discount.
  • Use the rest operator to collect all remaining arguments into an array called prices.
  • Calculate the sum of the prices, subtract the discount, and return the total.

Answer

Code: