2 min read

ES6+ Features

ECMAScript 2015 (ES6) was a major update to JavaScript, and it introduced a lot of new features that have become standard in modern JavaScript development. Subsequent yearly updates (ES7, ES8, etc.) have added even more features.

Here are some of the most important ES6+ features:

let and const

let and const are new ways to declare variables. They are block-scoped, which means they are only available within the block of code where they are defined (e.g., inside an if statement or a for loop).

  • let: Allows you to declare a variable that can be reassigned.
  • const: Allows you to declare a variable that cannot be reassigned.

Arrow Functions

Arrow functions provide a more concise syntax for writing functions.

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

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

Arrow functions also have a lexical this, which means that this refers to the this of the surrounding code, not the function itself.

Template Literals

Template literals allow you to embed expressions in strings. They are created using backticks (`).

const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, John!"

Destructuring

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

// Array destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c); // 1 2 3

// Object destructuring
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name, age); // "John" 30

Default Parameters

You can now provide default values for function parameters.

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

greet(); // "Hello, Guest!"
greet('John'); // "Hello, John!"

Spread and Rest Operators

The spread operator (...) allows you to expand an iterable (like an array or object) into individual elements. The rest operator (...) allows you to collect multiple elements into an array.

// Spread operator
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]

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

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

Classes

ES6 introduced a new syntax for creating classes in JavaScript. It is syntactic sugar over JavaScript's existing prototype-based inheritance.

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

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

const john = new Person('John', 30);
john.greet(); // "Hello, my name is John."