In this article, we are going to learn and master all the JavaScript ES6 concepts and methods with lots of code examples.

JavaScript ES6 Concepts with Examples
JavaScript ES6 Concepts with Examples

ECMAScript 2015, also known as ES6, is a major update to the JavaScript language that brought many new features and improvements to the language.

With ES6, developers gained access to new syntax for declaring variables, writing functions, working with objects and arrays, and much more. ES6 introduced a lot of new features that made writing JavaScript code much more powerful, concise, and easier to read.

In this article, we’ll explore some of the most important new features introduced in ES6 with code examples to help you understand how to use them in your own code.

ES6 Topics covered in this article:

  • let and const for block-scoped variables
  • Arrow functions for concise function syntax
  • Template literals for interpolated strings
  • Destructuring assignment for extracting values from arrays and objects
  • Spread syntax for expanding iterables into individual elements
  • Object property shorthand for concise object property definition
  • Classes for defining object blueprints
  • Promises for easier asynchronous programming
  • Default parameters for setting default values in function parameters
  • Rest parameters for passing an arbitrary number of arguments to a function
  • Modules for organizing code into separate files and exporting/importing functionality
  • Map and Set data structures for more efficient data manipulation
  • Symbol data type for creating unique values
  • for...of loop for iterating over iterable objects
  • async/await for easier asynchronous programming with promises

1. let and const declarations:

ES6 introduced two new variable declarations, let and const. They are used to declare variables but are block-scoped, meaning they only exist within the block they were declared in.

The let keyword is used to declare variables that can be reassigned:

let a = 10;
a = 20;
console.log(a); // Output: 20

The const keyword is used to declare variables that cannot be reassigned:

const b = "Hello";
console.log(b); // Output: Hello

2. Arrow Functions

Arrow functions are a shorthand syntax for writing function expressions. They use a concise syntax and automatically bind this to the surrounding code.

Here’s an example of a traditional function expression:

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

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

And here’s the equivalent code using an arrow function:

const add = (a, b) => a + b;
console.log(add(3, 5)); // Output: 8

Arrow functions can also be used with object literals to create shorthand methods:

const person = {
  name: "John",
  age: 30,
  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.sayHello(); // Output: Hello, my name is John

3. Template Literals

Template literals allow for embedded expressions and multiline strings using backticks (`).

See also  Top 50 Node JS Interview Questions And Answers

Here’s an example:

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

This will output: Hello John!

Template literals can also be used for multiline strings:

const message = `This is a
multi-line
string.`;

console.log(message);

This will output:

This is a
multi-line
string.

4. Destructuring Assignment:

Destructuring assignment allows you to extract values from arrays or objects and assign them to variables.

Here’s an example with an array:

const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a, b, c); // Output: 1 2 3

And here’s an example with an object:

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

Destructuring assignment can also be used with default values:

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

5. Spread Operator

The spread operator ... allows an iterable to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Here’s an example with an array:

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

And here’s an example with a function call:

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

const arr = [1

6. Object Property Shorthand

ES6 introduced a shorthand syntax for defining object properties when the property and variable names are the same.

Here’s an example:

const name = "John";
const age = 30;

const person = { name, age };

console.log(person); // Output: { name: "John", age: 30 }

7. Classes:

ES6 introduced a new way to define classes using the class keyword. Classes in JavaScript are syntactic sugar over the existing prototype-based inheritance.

Here’s an example:

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

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

const john = new Person("John", 30);
john.sayHello(); // Output: Hello, my name is John

8. Promises:

Promises provide a way to write asynchronous code that’s easier to read and reason about.

See also  JavaScript String Methods Complete Guide

Here’s an example:

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { name: "John", age: 30 };
      resolve(data);
    }, 2000);
  });
}

getData()
  .then(data => console.log(data))
  .catch(error => console.log(error));

This will output:

{ name: "John", age: 30 }

9. Default Parameters:

Default parameters allow you to set default values for function parameters.

Here’s an example:

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

greet(); // Output: Hello, World!
greet("John"); // Output: Hello, John!

10. Rest Parameters:

Rest parameters allow you to pass an arbitrary number of arguments to a function.

Here’s an example

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

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

11. Spread Syntax:

The spread syntax allows you to expand an iterable (e.g., an array, string, or object) into individual elements.

Here’s an example:

const numbers = [1, 2, 3];
console.log(...numbers); // Output: 1 2 3

const string = "hello";
console.log(...string); // Output: h e l l o

const obj1 = { x: 1, y: 2 };
const obj2 = { ...obj1, z: 3 };
console.log(obj2); // Output: { x: 1, y: 2, z: 3 }

12. Modules:

Modules allow you to organize your code into separate files and export and import functionality between them.

Here’s an example:

// utils.js
export function add(a, b) {
  return a + b;
}

// app.js
import { add } from "./utils.js";
console.log(add(1, 2)); // Output: 3

13. Map and Set data structure

Both Map and Set are data structures in computer science that are used to store and manage collections of values.

Map is an ordered collection of key-value pairs where each key is unique. It is also known as a dictionary, hash table, or associative array in other programming languages. A key-value pair is an association between a key and its corresponding value.

Here’s an example of how to use Map in JavaScript:

// Create a new Map object
let myMap = new Map();

// Add some key-value pairs to the Map
myMap.set('apple', 1);
myMap.set('banana', 2);
myMap.set('orange', 3);

// Get the value associated with a specific key
console.log(myMap.get('apple')); // Output: 1

// Check if a key exists in the Map
console.log(myMap.has('banana')); // Output: true

// Remove a key-value pair from the Map
myMap.delete('orange');

// Iterate over the Map using for...of loop
for (let [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// Output:
// apple = 1
// banana = 2

Set is an unordered collection of unique values. It is useful for storing a collection of elements with no duplicates.

See also  JavaScript Spread Operator Examples

Here’s an example of how to use Set in JavaScript:

// Create a new Set object
let mySet = new Set();

// Add some values to the Set
mySet.add(1);
mySet.add(2);
mySet.add(3);

// Check if a value exists in the Set
console.log(mySet.has(2)); // Output: true

// Remove a value from the Set
mySet.delete(3);

// Iterate over the Set using for...of loop
for (let value of mySet) {
  console.log(value);
}
// Output:
// 1
// 2

Map and Set data structures provide different functionalities to help manage collections of values in computer science.

14. Symbol data structure

In JavaScript, the Symbol is a primitive data type introduced in ECMAScript 2015 (ES6) that represents a unique identifier. A Symbol value can be used as an object property key, which allows you to create non-enumerable properties on an object that cannot be accessed or modified accidentally.

Unlike other primitive data types, Symbol values cannot be instantiated with the new keyword. Instead, you create a Symbol value by calling the Symbol() function, optionally passing a string as a description:

const mySymbol = Symbol('mySymbol description');

Example of JavaScript Symbol

const mySymbol = Symbol('mySymbol description');

const myObject = {
  [mySymbol]: 'This is a value for mySymbol',
  anotherProp: 'This is another property'
};

console.log(myObject[mySymbol]); // Output: "This is a value for mySymbol"
console.log(Object.keys(myObject)); // Output: ["anotherProp"]

15. Async/Await

ES6 introduced a new way of working with asynchronous code called async/await. The async/await syntax allows you to write asynchronous code that looks and behaves more like synchronous code, making it easier to read and reason about.

Here’s an example of how to use async/await:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function doSomethingAsync() {
  console.log('Starting...');
  await delay(2000); // wait for 2 seconds
  console.log('...Done!');
}

doSomethingAsync(); // Output: "Starting..." (wait for 2 seconds) "...Done!"

You can also use try/catch blocks with async/await to handle errors

async function doSomethingAsync() {
  try {
    console.log('Starting...');
    await delay(2000); // wait for 2 seconds
    console.log('...Done!');
  } catch (error) {
    console.error(error);
  }
}

doSomethingAsync();

16. for…of loop

The for...of loop is a new type of loop introduced in ECMAScript 2015 (ES6) for iterating over iterable objects such as arrays, strings, maps, sets, and more.

Here’s an example of how to use for...of to loop over an array

const myArray = ['apple', 'banana', 'orange'];

for (const element of myArray) {
  console.log(element);
}

// Output:
// "apple"
// "banana"
// "orange"