Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ES6?
3.
The const keyword
4.
The let keyword
5.
Arrow functions
6.
Template literal
7.
Multi-line Strings
8.
Default parameters
9.
Destructuring assignments
10.
The For/Of Loop
11.
Promises
12.
Classes
13.
Modules
14.
Frequently Asked Questions
14.1.
What is ES6?
14.2.
How is ES6 different from Javascript?
14.3.
What is the use of ES6?
15.
Conclusion
Last Updated: Mar 27, 2024
Easy

ES6 Features

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

ES6 is the 6th edition of the ECMAScript, introduced in 2015. The first edition was released in 1997. Many new features were included in this release, including modules, class, iterators, arrow functions, for/of loops, typed arrays, promises, reflection, and more. Nowadays, many communities support ES6 more than ES5 as it is less time-consuming than ES5. Because of several new features and the shorthand storage implementation, ES6 has a better performance than ES5.

What is ES6?

ES6, also known as ECMAScript2015, is the 6th and most significant edition of the ECMAScript language specification standard. It brought about major changes to the Javascript language. It introduced several new features like the const and let keyword, rest and spread operators, classes, template literals, modules, and many other enhancements to make JavaScript programming fun and easier to understand. It is true to say that the phrase "write less, do more" perfectly suits the ES6 features. Let us describe these features in detail:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

The const keyword

In ES5, we used to declare variables via var. In ES6, the const and let keywords were introduced to store variables. Generally, a const keyword is used to store variables whose value always remains fixed. In javascript, a const keyword is more potent than var, as once used, its value is not going to be changed. It is immutable. However, it is mutable when used with objects.

Code:

// Using Const
const a = 5;
console.log(a); // Will print 5 to the console.

// Trying to reassign a const variable
a=10;
console.log(a); // Will give TypeError.

 

Output:

The let keyword

With the "let" keyword, the variables declared will be mutable. The only contrast between "var" and "let" is scoping, which makes it a better alternative as compared to "var." The "let" variables and constants have a block scope which is surrounded by curly braces "{}" and cannot be used before declaration.

Code:

// Using let
let a = 5;
console.log(a); // 5

a = 10;
console.log(a); // 10

 

Output:

Arrow functions

Another exciting feature of ES6 is the arrow function. It provides a more concise and clear syntax for writing function expressions by making the "function" and "return" keywords optional. 

They are defined using the fat arrow (=>) notation and make the code more modern and readable.

Code:

// Function Expression in ES5
var sum = function(a, b) {
    return a + b;
}
console.log(sum(2, 3)); // 5

// Function Expression using arrow function in ES6
var sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5

 

Output:

Template literal

In ES5, the "+" operator was used whenever we wanted to concatenate strings or use variables inside a string. With ES6, we use a new syntax, ${PARAMETER}, which is used inside of the back-ticked string. This improves code readability and helps us to work with strings in a better way.

Code:

// Creating string using variables and expression in ES5
var a = 10;
var b = 20;
var result1 = 'The sum of ' + a + ' and ' + b + ' is ' + (a+b) + '.';
console.log(result1); // The sum of 10 and 20 is 30.

//Creating string using variables and expression in ES6
let c = 10;
let d = 20;
let result2 = `The sum of ${c} and ${d} is ${c+d}.`;
console.log(result2);// The sum of 10 and 20 is 30.

 

Output:

Multi-line Strings

Multi-line strings can be created in ES6 with just the help of back-ticks.

Code:

let greeting = `Hello learners,    
                Greetings to all,
                You are learning about ES6 features.!`
 console.log(greeting);

 

Output:

Default parameters

In ES6, users can specify the default values right in the signature of the functions. It means if no argument is provided to the called function, then the value of the default parameter will be used. In ES5, we used the OR operator.

Code:

console.log("In ES5");
function greet(name='Morning') {
    return `Good ${name}!`;
}
console.log(greet()); // Good Morning!
console.log(greet('Evening')); // Good Evening!


console.log("In ES6");
function greet(name) {
    var name = name || 'Morning'; 
    return 'Good ' +  name + '!';
}
console.log(greet()); // Good Morning!
console.log(greet('Evening')); // Good Evening!

 

Output:

Destructuring assignments

The destructuring feature of ES6 makes it easy to extract values from an array and properties from objects into distinct variables. It means breaking down a complex structure (Objects or arrays) into simpler parts.

Code:

// ES5 syntax
console.log("In ES5");
var months = ["May", "June"];

var a = months[0];
var b = months[1];

console.log(a); // May
console.log(b); // June


// ES6 syntax
console.log("In ES6");
let fruits = ["May", "June"];

let [c, d] = months; // Array destructuring assignment


console.log(c); // May
console.log(d);// June

 

Output:

The For/Of Loop

The new for...of loop allows us to iterate over arrays or other iterable objects very easily. Also, the code inside the loop is executed for each element of the iterable object. Here's an example:

Code:

// Iterating over string
let greet = "Hello World!";

for(let character of greet) {
    console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
}

 

Output:

Promises

First-class representation of a value that may be made asynchronously and be available in the future. 

Code:

function msgAfterTimeout (msg, who, timeout) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${msg} Coding ${who}!`), timeout)
    })
}
msgAfterTimeout("", "Ninjas#01", 100).then((msg) =>
    msgAfterTimeout(msg, "Ninjas#02", 200)
).then((msg) => {
    console.log(`done after 300ms:${msg}`)
})

 

Output:

Classes

Classes never existed in ECMAScript5 or earlier. They were introduced in ES6, which looked similar to classes in other object-oriented languages, such as Java, PHP, etc.

In ES6, the keyword “class” is used to declare a class, followed by the name of the class.

Code:

// classes in ES6
class Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}

const man1 = new Person('Ninja','21');
const man2 = new Person('Warrior','20');

console.log(man1.name); // Ninja
console.log(man2.name); // Warrior

 

Output:

Modules

Earlier in ES5, there was no native support for modules in JavaScript. For example, everything inside a JavaScript application, such as variables across different JavaScript files, shared the same scope.

ES6 introduces a file-based module in which a separate .js file represents each module. After that we were able to use the export or import statement in a module to export or import variables, functions, classes, or any other entity to/from other modules or files.

First, we create a Javascript file named main.js-

let name = "Ninja#01";
const age = 20; 

function multiplyNumbers(a, b) {
    return a * b;
}

// Exporting variables and functions
export { name, age, multiplyNumbers };

 

Then we create another Javascript file named app.js:

import { name, age, multiplyNumbers } from './main.js';

console.log(name); // Ninja#01
console.log(age); // 20
console.log(addNumbers(5, 15)); // 20

 

At last we create a HTML file "test.html" and open this HTML file in your browser using HTTP protocol (or use localhost). Also notice the type="module" on the script tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>ES6 Module Demo</title>
</head>
<body>
    <script type="module" src="app.js"></script>
</body>
</html>

Frequently Asked Questions

What is ES6?

JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer version of JavaScript that was introduced in 2015. ECMAScript provides the specification on how the JavaScript programming language should work.

How is ES6 different from Javascript?

The ECMAScript specification provides a blueprint for creating a scripting language like Javascript, Jscript etc, while JavaScript is an implementation of that blueprint.

What is the use of ES6?

JavaScript ES6 brings new features and syntax to make our code more readable and modern. It allows us to write less and do more. 

Conclusion

I hope this blog helped you provide some meaningful insights on ECMAScript2015 and the standard for Javascript implementation. We also learned about the top ES6 features such as const, let keywords, arrow functions, template literals, classes, and modules, which makes ES6 so popular and makes working with Javascript easier.

Recommended Readings:

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, interview puzzles, take a look at the interview experiences, and interview bundle for placement preparations.

We hope that this blog has helped you enhance your knowledge regarding Javascript, and if you liked this blog, check other links. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass