JavaScript ES6 Features

Learn about important ES6 features that modernize JavaScript development.

Introduction to ES6

ES6 (ECMAScript 2015) introduced powerful features that make JavaScript cleaner and more readable. Let's explore the most useful ones.

Let and Const:

let allows block-scoped variables; const is block-scoped and immutable.


let age = 25;
age = 26;

const pi = 3.14;
// pi = 3.14159; ❌ Error
            

Arrow Functions:

Shorter syntax and lexical this binding.


const add = (a, b) => a + b;

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

Template Literals:

Use backticks ` and ${variable} inside strings.


let name = "Alice";
let msg = `Welcome, ${name}!`;
console.log(msg); // Welcome, Alice!
            

Destructuring:

Unpack values from arrays or objects into variables.


// Array
let [a, b] = [10, 20];

// Object
let {name, age} = {name: "John", age: 30};
            

Spread & Rest Operators

... is used for both expanding and collecting values.


let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

function total(...nums) {
  return nums.reduce((a, b) => a + b);
}
            

Promises:

const promise = new Promise((resolve, reject) => {
    // async code
});

Default Parameters

Set default values for function parameters:


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

greet(); // Hello, Guest
greet("Shyam"); // Hello, Shyam
            

Practice Task

Use arrow functions, template literals, and destructuring in one example:


const user = { name: "Ravi", age: 28 };

const welcome = ({ name }) => {
  return `Welcome, ${name}!`;
};

console.log(welcome(user));