The Wayback Machine - https://web.archive.org/web/20240712061002/https://www.geeksforgeeks.org/introduction-to-es6/
Open In App

Introduction to ES6

Last Updated : 04 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language. ECMAScript is the standardization of Javascript which was released in 2015 and subsequently renamed as ECMAScript 2015.
ECMAScript and Javascript are both different.

Introduction-to-ES6-copy

ECMAScript vs JavaScript

ECMAScript: It is the specification defined in ECMA-262 for creating a general-purpose scripting language. In simple terms, it is a standardization for creating a scripting language. It was introduced by ECMA International and is an implementation with which we learn how to create a scripting language. 

JavaScript: A general-purpose scripting language that confirms the ECMAScript specification. It is an implementation that tells us how to use a scripting language.

ES6

ES6

Javascript ES6 has been around for a few years now, and it allows us to write code in a clever way which basically makes the code more modern and more readable. It’s fair to say that with the use of ES6 features we write less and do more, hence the term ‘write less, do more’ definitely suits ES6. 

ES6 introduced several key features like const, let, arrow functions, template literals, default parameters, and a lot more. Let’s take a look at them one by one.

const

The const keyword is used to declare constant variables whose values can’t be changed. It is an immutable variable except when used with objects.

Example: The below example will explain you the use of const keyword in different situations.

javascript
// Const 
const name = 'Mukul';
console.log(name); 
// Will print 'Mukul' to the console.

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

// Trying to declare const variable first
// and then initialise in another line
const org_name;
org_name = "GeeksforGeeks";
console.log(org_name);
// Throws an syntax error: missing initializer in const declaration

let

The let variables are mutable i.e. their values can be changed. It works similar to the var keyword with some key differences like scoping which makes it a better option when compared to var.

Example: This example will illustrate how to declare varibale using the let keyword.

javascript
// let
let name = 'Mukul';
console.log(name); 
// Prints Mukul

name = 'Rahul';
console.log(name); 
// Prints Rahul

// Trying to declare let variable first and then initialise in another line
let org_name;
org_name = "GeeksforGeeks";
console.log(org_name); 
// Prints GeeksforGeeks

Output
Mukul
Rahul
GeeksforGeeks

Arrow functions

Arrow functions are a more concise syntax for writing function expressions. These function expressions make your code more readable, and more modern. 

Example: The below example will show you how the arrow functions can be created and implemented.

javascript
// Function declaration using function keyword
function simpleFunc(){
    console.log("Declared using the function keyword");
}
simpleFunc(); 

// Function declared using arrow functions
const arrowFunc = () => {
    console.log("Declared using the arrow functions");
}
arrowFunc();

Output
Declared using the function keyword
Declared using the arrow functions

Template literal

It allows us to use the JavaScript variables with the string without using the ‘+’ operator. Template literal defined using (“) quotes.

Example: This example will explain the practical use of template literals.

javascript
// Without Template Literal
var name = 'GeeksforGeeks';
console.log('Printed without using Template Literal'); 
console.log('My name is '+ name); 

// With Template Literal
const name1 = 'GeeksforGeeks';
console.log('Printed by using Template Literal');
console.log(`My name is ${name1}`); 

Output
Printed without using Template Literal
My name is GeeksforGeeks
Printed by using Template Literal
My name is GeeksforGeeks

Object and Array Desctructuring

Destructing in javascript basically means the breaking down of a complex structure(Objects or arrays) into simpler parts. With the destructing assignment, we can ‘unpack’ array objects into a bunch of variables.

Example: The below example will explain how the destructuring can be done in ES6.

javascript
// Object Destructuring
const college = {
    name : 'DTU',
    est : '1941',
    isPvt : false
};
let {name, est, isPvt} = college;
console.log(name, est, isPvt);

// Array Destructuring
const arr = ['lionel', 'messi', 'barcelona'];
let[value1,value2,value3] = arr;
console.log(value1, value2, value3);

Output
DTU 1941 false
lionel messi barcelona

Default Parameters

In ES6, we can declare a function with a default parameter with a default value.

Example: This example will show how to define default paramters for a function.

javascript
function fun(a, b=1){
    return a + b;
}
console.log(fun(5,2));
console.log(fun(3));

Output
7
4

Classes

ES6 introduced classes in JavaScript. Classes in javascript can be used to create new Objects with the help of a constructor, each class can only have one constructor inside it. 

Example: The below example will show how to create classes in ES6.

javascript
// classes in ES6
class Vehicle{
    constructor(name,engine){
        this.name = name;
        this.engine = engine;
    }
}

const bike1 = new Vehicle('Ninja ZX-10R','998cc');
const bike2 = new Vehicle('Duke','390cc');

console.log(bike1.name); // Ninja ZX-10R
console.log(bike2.name); // Duke

Output
Ninja ZX-10R
Duke

Rest parameter and spread operator

Rest Parameter: It is used to represent a number of parameter in an array to pass them together to a function.

Example: This example will illustrate the practical use of the Rest paramter.

javascript
// ES6 rest parameter
function fun(...input){
    let sum = 0;
    for(let i of input){
        sum += i;
    }
    return sum;
}
console.log(fun(1,2)); // 3
console.log(fun(1,2,3)); // 6 
console.log(fun(1,2,3,4,5)); // 15

Output
3
6
15

Spread Operator: It simply changes an array of n elements into a list of n different elements.

Example: The below example will explain the practical implementation of the Spread Operator.

javascript
// Spread operator
let arr = [1,2,3,-1];
console.log(...arr);
console.log(Math.max(...arr)); // -1

Output
1 2 3 -1
3

for/of Loop

The for/of loop allows you to iterate through the iterable items but in a short syntax as compared to other loops.

Example: The for/of loop is implemented in the below code example with an array.

JavaScript
const myArr = [5, 55, 33, 9, 6]
for(let element of myArr){
    console.log(element);
}

Output
5
55
33
9
6

JavaScript Maps and Sets

Map: The maps in JavaScript are used to store multiple items in the form of key-value pairs. The keys of a map can be of any datatype.

Set: A set consist of only unique value, a value can be stored only once in a set. It can store any value of any datatype.

Example: The below example will explain the use of both the JavaScript Map and Set practically.

JavaScript
// Maps in JavaScript
const myMap = new Map([
    ["stringKey", 23], 
    [48, "numberedKey"]
]);
myMap.set(false, 0);
myMap.set(1, true);
console.log(myMap.get("stringKey"), 
    myMap.get(48), myMap.get(false), 
    myMap.get(1));

// Sets in JavaScript
const mySet = 
    new Set(["string value", "string value"]);
mySet.add(24);
mySet.add(24);
mySet.add(3);
console.log(mySet);

Output
23 numberedKey 0 true
Set(3) { 'string value', 24, 3 }

Promises

JavaScript promises are used to perform the asynchronous tasks, that takes some time to get executed. It combines the synchronous and asynchronous code together.

Example: The below example will show how you can create and implement a promise in JavaScript.

JavaScript
const JSpromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Promise is Working")
    }, 2000);
});

JSpromise.then((value) => {console.log(value)});

Output
Promise is Working

Symbol

Symbol is a type of primitive data type intriduced in ES6. It is used to specify the hidden identifiers that can not be directly accessed by any other code.

Example: The use of the Symbol data type is explained in the below code example.

JavaScript
const gfg = {
    name: "GeeksforGeeks",
    desc: "A Computer Science portal for all geeks."
}

let short_name = Symbol("short_name")
gfg.short_name = "GFG";
console.log(`${gfg.name}, \n${gfg.desc}`);
console.log(`Company's Short Name using gfg.short_name: ${gfg.short_name} `)
console.log(`Company's Short Name using gfg[short_name]: ${gfg[short_name]} `)

Output
GeeksforGeeks, 
A Computer Science portal for all geeks.
Company's Short Name using gfg.short_name: GFG 
Company's Short Name using gfg[short_name]: undefined 

String Methods

Example: The below code example will illustrate the use of all the string methods introduced in ES6.

JavaScript
// String startsWith()
const useStart = "This string implements the startsWith() method.";
console.log(useStart.startsWith("This string"), 
useStart.startsWith("This is"));

// String endsWith()
const useEnd = "This string implements the endsWith() method.";
console.log(useEnd.endsWith("clear() method."), 
useEnd.endsWith("method."));

// String includes()
const useIncludes = "This string implements the includes() method.";
console.log(useIncludes.includes("includes()"), 
useIncludes.includes("My name"));

Output
true false
false true
true false

Array Methods

Example: The below code example implements all array methods introduced in ES6.

JavaScript
// Array.from() method
const newArr = Array.from("GeekdforGeeks");
console.log("Implementing Array.from(): ", newArr)

// Array.keys() method
const milkProducts = ["Curd", "Cheese", "Butter", "Ice-Cream"];
const arrayKeys = milkProducts.keys();
console.log("Implementing Array.keys(): ")
for(let key of arrayKeys){
    console.log(key)
}

// Array.find() method
const findArray = ["clock", "strong", "planet", "earth"];
const lessThanSix = (item) => {
    return item.trim.length < 6;
}
console.log("Implementing Array.find(): ", 
findArray.find(lessThanSix));
console.log("Implementing Array.findIndex(): ", 
findArray.findIndex(lessThanSix));

Output
Implementing Array.from():  [
  'G', 'e', 'e', 'k',
  'd', 'f', 'o', 'r',
  'G', 'e', 'e', 'k',
  's'
]
Implementing Array.keys(): 
0
1
2
3
Implementing Array.find():  clock
Implementing Array.findInd...

Object Enteries

Object.entries() method is used to convert a single valued array into an array object with a key-value pair as array items.

Example: The below example implements the object.entries() method practically.

JavaScript
const myArr = 
    ["GeeksforGeeks", "A Computer Science Portal for all geeks"];

const arr = myArr.entries()
for(let item of arr){
    console.log(item);
}

Output
[ 0, 'GeeksforGeeks' ]
[ 1, 'A Computer Science Portal for all geeks' ]


Previous Article
Next Article

Similar Reads

ES6 RegEx
A RegEx is the short form of the Regular Expression, which is the sequence of characters that define a pattern. The characters in a RegEx can be alphabets, numbers or special characters. Usually, RegEx is used to find a pattern in a string to replace, delete or modify them. In ES6, a RegEx can be defined by 2 different notations. Literal notation:
3 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the following syntax: function functionName(arg1, arg2….) {
4 min read
ES6 Top features and syntax
ES6 or as it is officially called: ECMAScript2015 is a new JavaScript implementation and is arguably the hottest topic in the JS developer's conventions and meetups why it should not be: JavaScript rules the web and is gaining a foothold in every other field possible, be it robotics(nodebots), desktop applications(using ion framework), chatbots, et
3 min read
ES6 Promises
Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from any site to deliver it to your place that order record will be the promise and the food will be the value of that promise. So the order details are the cont
4 min read
Motivation to bring symbols in ES6
Javascript comprised six datatypes undefined, null, boolean, String, Number and Object (includes array datatype). The Symbol is newly introduced datatype in ES6 also known as JavaScript 6, which makes the total number of data types in JavaScript is 7. It is a primitive datatype which means Symbol cannot be instantiated. Symbols are immutable dataty
3 min read
ES6 | Array filter() Method
The Array filter() is an inbuilt method, this method creates a new array with elements that follow or pass the given criteria and condition. Few Examples have been implemented below for a better understanding of the concept Syntax: var newArray = arr.filter(callback(element[, index[, array]]) [, thisArg]) Parameter: This method accepts 2 parameters
2 min read
ES6 Math
The ES6 Math object contains so many properties and methods to perform some mathematical functions. The ES6 is an object that can be called without creating it. With the help of ES6 Math in JavaScript, you can store integers in the form of binary and octal notation. There are so many properties and functions available in ES6 Math. Also in the funct
4 min read
ES6 Number
The ES6 Number contains so many properties and methods to perform some numeric functions, that contains the date, integers, and floating points, etc. The ES6 is an object that can be called without creating it. With the help of ES6 Number in JavaScript, you can work with number objects so easily because the browsers convert number literals to insta
3 min read
ES6 | Array forEach() Method
When working with arrays, it's widespread to iterate through its elements and manipulate them. Traditionally this can be done using for, while or do-while loops. The forEach will call the function for each element in the array. Syntax: array.forEach( callback, thisObject ) Parameter: This method accept only two parameter mentioned above and describ
3 min read
ES6 Dialog Boxes
ES6 has three types of dialog boxes. These dialog boxes are used for various purposes as mentioned below: Raise an alert that alert function is used to accomplish the task.Get confirmation of an event or input - confirm function is used to accomplish the task.Get an input from the user -prompt function is used to accomplish the task. Alert Dialog B
3 min read
three90RightbarBannerImg