DEV Community

Shajibul Alam Shihab
Shajibul Alam Shihab

Posted on

Javascript ES6 (ECMAScript 2015) Features

ES6 also known as ECMAScript 2015 is a major update to JavaScript, and it introduced many new features that make JavaScript more powerful and easier to work with. Whether you're a beginner or an experienced developer, understanding ES6 is essential for modern web development.

In this blog, we'll cover all the key features of ES6, including let and const, arrow functions, template literals, destructuring, spread and rest operators, classes, modules, and much more.

So, let's get started!


1. let and const

ES6 introduced two new ways to declare variables: let and const. Before ES6, we only had var, but var has some issues, especially with scope. Let's see how let and const solve these problems.

let is used for variables that can change their value, while const is used for variables that cannot be reassigned. Here's an example:

let name = "John";
name = "Doe"; // This is allowed

const age = 25;
age = 30; // This will throw an error
Enter fullscreen mode Exit fullscreen mode

The main difference between let and var is block scope. Variables declared with let are only accessible within the block they are defined in, while var is function-scoped. For example:

if (true) {
  let x = 10;
  var y = 20;
}
console.log(x); // Error: x is not defined
console.log(y); // 20
Enter fullscreen mode Exit fullscreen mode

So, always use let and const instead of var in modern JavaScript.


2. Arrow Functions

Next, let's talk about arrow functions. Arrow functions are a shorter and more concise way to write functions in JavaScript. They also handle the this keyword differently.

Here's a comparison between a regular function and an arrow function:

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

// Arrow function
const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Arrow functions are especially useful for callback functions. For example:

const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
Enter fullscreen mode Exit fullscreen mode

One important thing to note is that arrow functions do not have their own this. Instead, they inherit this from the surrounding context. This makes them ideal for use in methods like setTimeout or event listeners.


3. Template Literals

ES6 introduced template literals, which make it easier to work with strings. Instead of using single or double quotes, we use backticks (`). Template literals allow us to embed expressions inside strings using ${}.

Here's an example:

const name = "John";
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // My name is John and I am 25 years old.
Enter fullscreen mode Exit fullscreen mode

Template literals also support multi-line strings without needing to use \n:

const html = `
  <div>
    <h1>Hello, World!</h1>
  </div>
`;
Enter fullscreen mode Exit fullscreen mode

This makes our code much cleaner and easier to read."


4. Destructuring

Destructuring is a powerful feature in ES6 that allows us to extract values from arrays or objects into variables. Let's start with array destructuring:

const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Enter fullscreen mode Exit fullscreen mode

We can also use destructuring with objects:

const person = { name: "John", age: 25 };
const { name, age } = person;
console.log(name); // John
console.log(age); // 25
Enter fullscreen mode Exit fullscreen mode

Destructuring is very useful when working with functions that return multiple values or when dealing with complex data structures.


5. Spread and Rest Operators

The spread operator (...) allows us to expand an array or object into individual elements. For example:

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

We can also use the spread operator to copy objects:

const person = { name: "John", age: 25 };
const newPerson = { ...person, city: "Dhaka" };
console.log(newPerson); // { name: "John", age: 25, city: "Dhaka" }
Enter fullscreen mode Exit fullscreen mode

The rest operator is used to collect multiple elements into an 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)); // 6
Enter fullscreen mode Exit fullscreen mode

These operators are very versatile and can simplify many tasks in JavaScript.


6. Classes

ES6 introduced classes, which provide a cleaner and more structured way to work with objects and inheritance. Here's an example of a class:

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", 25);
john.greet(); // Hello, my name is John
Enter fullscreen mode Exit fullscreen mode

We can also use inheritance with the extends keyword:

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying`);
  }
}

const alice = new Student("Alice", 20, "A");
alice.greet(); // Hello, my name is Alice
alice.study(); // Alice is studying
Enter fullscreen mode Exit fullscreen mode

Classes make it easier to organize and reuse code in JavaScript.


7. Modules

ES6 introduced a native module system for JavaScript. With modules, we can split our code into multiple files and import/export functionality as needed.

Here's an example of exporting and importing:

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import { add, subtract } from './math.js';
console.log(add(2, 3)); // 5
console.log(subtract(5, 2)); // 3
Enter fullscreen mode Exit fullscreen mode

We can also use default exports:

// math.js
export default function multiply(a, b) {
  return a * b;
}

// main.js
import multiply from './math.js';
console.log(multiply(2, 3)); // 6
Enter fullscreen mode Exit fullscreen mode

Modules help us keep our code organized and maintainable.


8. Promises and Async/Await

ES6 introduced Promises to handle asynchronous operations in a more elegant way. A Promise represents a value that may be available now, in the future, or never.

Here's an example of a Promise:

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched!");
    }, 2000);
  });
};

fetchData().then((data) => console.log(data)); // Data fetched!
Enter fullscreen mode Exit fullscreen mode

ES7 introduced async/await, which makes working with Promises even easier:

const fetchData = async () => {
  const data = await fetchData();
  console.log(data); // Data fetched!
};
Enter fullscreen mode Exit fullscreen mode

Async/await allows us to write asynchronous code that looks like synchronous code, making it easier to read and debug.


We've covered all the major features of ES6, including let and const, arrow functions, template literals, destructuring, spread and rest operators, classes, modules, and Promises and async/await. These features make JavaScript more powerful and easier to work with, and they are essential for modern web development.

This post was created using AI. But the planning, presentation and final editing of each piece is the result of my own efforts.

Thank you

Top comments (0)