JS 2015 or ECMAScript 6 (ES6)
JS 2015 (ES6) also known as ECMAScript 6 (ES6), ECMAScript 6 (ES6) is a significant update to JavaScript, introducing arrow functions, classes, template literals, let and const for variable declaration, enhanced object literals, destructuring, and more modern features for better code organization and readability.
ECMAScript 6 (ES6) New Features
Name |
Description |
let keyword |
It is used to declare variables in JavaScript that are block-scoped. |
const keyword |
It is used to declare variables with immutable values. |
Arrow Functions |
It defines anonymous functions in JavaScript. |
The … Operator |
Spread/rest operator unpacks elements (spread) or gathers (rest) them conveniently. |
For/of |
Iterates over values in iterable objects like arrays, and strings. |
Map Objects |
It stores key-value pairs, allowing any key type. |
Set Objects |
It stores unique values, preventing duplicates. |
Classes |
It is used to define blueprints for creating objects. |
Promises |
Manage asynchronous operations, simplifying callbacks and async handling. |
Symbol |
It is unique, immutable, used for private property keys. |
Default Parameters |
Sign values when function arguments are not provided explicitly. |
Function Rest Parameter |
Collects function arguments as an array for flexible parameter handling. |
String.includes() |
Checks if substring is present, returning true/false result. |
String.startsWith() |
Checks if string begins with specified substring, returning boolean. |
String.endsWith() |
Checks if string ends with provided substring, returning boolean. |
Array.from() |
Converts array-like/iterable objects to new array with optional mapping. |
Array keys() |
Iterates over array indices, allowing index-based iteration. |
Array find() |
Locates and returns the first array element satisfying a provided condition. |
Array findIndex() |
Retrieves the index of the first array element satisfying a given condition. |
New Math Methods |
Methods to perform some mathematical functions. |
New Number Properties |
Methods to perform some numeric functions, that contains the date, integers, and floating points, etc |
New Number Methods |
Number.isInteger() and Number.isSafeInteger() |
New Global Methods |
isFinite() and isNaN() |
Object entries |
Converts object properties to an array of [key, value] pairs |
JavaScript Modules |
Encapsulate code for better organization and reusability. |
Method 1: let and const keyword
- JavaScript let is a keyword used to declare variables in JavaScript that are block scoped.
- JavaScript const for declaring variables with immutable values, enhancing code stability and readability.
Syntax:
let variable_name = value; // let keyword
const const_name; // const leyword
const x;
Example: Here is the basic example of using let and const keyword.
Javascript
// Using let let x = 10; // Allowed, since x is declared with let x = 20; console.log(x); // Outputs: 20 // Using const const y = 5; y = 8; // Error! Cannot reassign a const variable console.log(y); |
Output:
20
TypeError: Assignment to constant variable.
Method 2: Arrow Function
Arrow functions were introduced in the ES6 version.Arrow functions are anonymous functions i.e. functions without a name and are not bound by an identifier. Arrow functions do not return any value and can be declared without the function keyword. They are also called Lambda Functions.
Syntax:
const gfg = () => {
console.log( "Hi Geek!" );
}
Example: herecis the basic example of arrow function.
Javascript
const gfg = () => { console.log( "Hi from GeekforBeginner!" ); } gfg(); |
Hi from GeekforBeginner!
Method 3: Spread Operator
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
Syntax:
let variablename1 = [...value];
Example: In this example, we are using spread operator to create arr2 with elements from arr1 and add 4, 5 and create obj2 by merging obj1 properties and adding c: 3, d: 4.
Javascript
// Spread operator with arrays let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Spread operator with objects let obj1 = { a: 1, b: 2 }; let obj2 = { ...obj1, c: 3, d: 4 }; console.log(obj2); |
[ 1, 2, 3, 4, 5 ] { a: 1, b: 2, c: 3, d: 4 }
Method 4: for/of Loop
The for…of loop in JavaScript iterates over iterable objects, like arrays, strings, for concise and readable element access and iteration.
Syntax:
for ( variable of iterableObjectName) {
. . .
}
Example: In this example, the for…of loop iterates over each element in the numbers array and logs each number to the console.
Javascript
const numbers = [1, 2, 3, 4, 5]; for (const num of numbers) { console.log(num); }; |
1 2 3 4 5
Method 5 : Map Objects
In JavaScript, a Map object holds key-value pairs, allowing any type of key, unlike objects. It maintains order and provides methods for manipulation and retrieval.
Syntax:
let map1 = new Map();
Example: Here is thew basic example of map object.
Javascript
let map1 = new Map(); map1.set( "FirstName" , "Rohit" ); map1.set( "LastName" , "Sharma" ); map1.set( "website" , "w3wiki" ); console.log(map1); |
Map(3) { 'FirstName' => 'Rohit', 'LastName' => 'Sharma', 'website' => 'w3wiki' }
Method 6: Set Objects
In JavaScript, a Set object stores unique values of any type. It ensures uniqueness, provides methods for manipulation, and doesn’t allow duplicate values within the set.
Syntax:
new Set( [it] );
Example: Here is the basic example of set object.
Javascript
const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(3); // Duplicate value, ignored mySet.add(2); console.log(mySet.has(1)); console.log(mySet.has(4)); mySet. delete (2); console.log(mySet.size); // Outputs: 2 |
true false 2
Method 7: Promises
Promises in JavaScript manage asynchronous operations, representing eventual results or errors. They simplify handling async code with methods like .then(), .catch(), and allow chaining.
Syntax:
const promise = new Promise((resolve,reject) => {....});
Example: In this example, The prom function returns a Promise based on the complete parameter, resolving with “success” if complete, and rejecting with “failed” otherwise.
Javascript
function prom(complete) { return prom = new Promise( function (resolve, reject) { console.log( "data iss fetching. please wait" ) if (complete) { resolve( "i am successfull" ) } else { reject( "i am failed" ) } }) } prom( true ).then((result) => console.log(result) ). catch ((error) => console.log(error)) |
data iss fetching. please wait i am successfull
Method 8: ES6 Symbol
ES6 Symbol is a unique, immutable data type used as object property keys, ensuring uniqueness. It’s primarily for internal/private use, avoiding unintended clashes in properties.
Syntax:
let symbol = Symbol();
Example: In this example, we are going to generate symbols.
Javascript
// Write Javascript code here let sym1 = Symbol() let sym2 = Symbol( 'mysymbol' ) console.log( 'Type of sym1: ' , typeof (sym1)) console.log( 'Type of sym2: ' , typeof (sym2)) |
Type of sym1: symbol Type of sym2: symbol
Method 9: Default Parameters
It is used to give the default values to the arguments, if no parameter is provided in the function call.
Syntax:
function fnName(param1 = defaultValue1, ..., paramN = defaultValueN) {
. . .
}
Example: In the below example, the first function gives result 7 whereas the second function call will be “undefined” as we did not pass any second argument.
Javascript
function add(a, b) { return a + b } console.log(add(5, 2)); // 7 console.log(add(5)); // NaN |
7 NaN
Method 10: Rest Parameter
In JavaScript, the rest parameter allows functions to accept an arbitrary number of arguments as an array, simplifying variable parameter handling and manipulation.
Syntax:
//... is the rest parameter (triple dots)
function functionname(...parameters) {
statement;
}
Example: In this example, the sum function accepts an arbitrary number of arguments using the rest parameter …numbers.
Javascript
function sum(...numbers) { let total = 0; for (const num of numbers) { total += num; } return total; } console.log(sum(1, 2, 3)); |
6
Method 11: String.includes() Method
The includes() method in JavaScript is used with strings to check if a specified substring is present, returning true if found, false if not.
Syntax:
string.includes( searchvalue, start )
Example: This method shows the basic use of the String includes() Method.
Javascript
let str = "Welcome to w3wiki." ; let check = str.includes( "Beginner" ); console.log(check); |
true
Method 12: String.startsWith() and String.endsWith() Methods
- The startsWith() method in JavaScript checks if a string starts with a specified substring, returning true if matched, otherwise false.
- The endsWith() method in JavaScript checks if a string ends with a given substring, returning true if matched, otherwise false.
Syntax:
str.startsWith( searchString , position ) // startsWith() method
str.endsWith(searchString, length) // endsWith() method
Example: Here is the basic example of above-mentioned method.
Javascript
let str1 = "Hello, Beginner!" ; console.log(str1.startsWith( "Hello" )); console.log(str1.startsWith( "Beginner" )); console.log(str1.endsWith( "Beginner!" )); console.log(str1.endsWith( "Hello" )); |
true false true false
Method 13: Array methods
- Array from() Method: It converts array-like or iterable objects into a new array with optional mapping function.
- Array keys() Method: It provides an iterator for array indices, allowing iteration over keys/indices in an array.
- Array find() Method: It locates and returns the first array element satisfying a provided condition.
- Array findIndex() Method: It retrieves the index of the first array element satisfying a given condition.
Example: In this example we are using the above mentioned methods one by one.
Javascript
const languages = [ "HTML" , "CSS" , "JavaScript" , "React.js" ]; // Using Array.from() to create a new array of lengths const lengths = Array.from(languages, lang => lang.length); console.log(lengths); // Outputs: [4, 3, 10, 7] // Using Array.keys() to iterate over array indices for (const index of languages.keys()) { console.log(`Index ${index}: ${languages[index]}`); } // Using Array.find() to find the first language // with length greater than 5 const longLanguage = languages.find(lang => lang.length > 5); console.log(longLanguage); // Outputs: "JavaScript" // Using Array.findIndex() to find the index of "React.js" const reactIndex = languages.findIndex( lang => lang === "React.js" ); console.log(reactIndex); // Outputs: 3 |
[ 4, 3, 10, 8 ] Index 0: HTML Index 1: CSS Index 2: JavaScript Index 3: React.js JavaScript 3
Method 14: New Math Methods
ES6 added the following methods to the Math object:
- Math.trunc() Method: It removes decimal fractions, returning the integer part of a number, effectively truncating it.
- Math.sign() Method: It returns the sign of a number as 1 (positive), -1 (negative), or 0 (zero).
- Math.cbrt() Method: It calculates the cubic root of a number, returning the value that, when cubed, equals the input.
- Math.log2() Method: It computes the base-2 logarithm of a positive number, indicating the power of 2 needed to obtain the input.
- Math.log10() Method: It calculates base-10 logarithm of a positive number, representing power of 10 for the input.
Example: Here we are use Math.trunc() and Math.sign() method.
Javascript
const num1 = [4.9, -7.2, 16, -25, 30, 100]; const truncatedNumbers = num1.map(num => Math.trunc(num)); console.log( "Truncated:" , truncatedNumbers); const signValues = num1.map(num => Math.sign(num)); console.log( "Sign:" , signValues); |
Truncated: [ 4, -7, 16, -25, 30, 100 ] Sign: [ 1, -1, 1, -1, 1, 1 ]
Example 2: In this example we are using Math.cbrt(),Math.log2() and Math.log10().
Javascript
const num2 = [8, -27, 16]; const cbrtRoots = num2.map(num => Math.cbrt(num)); console.log( "Cubic Roots:" , cbrtRoots); const log2Values = num2.map(num => Math.log2(Math.abs(num))); console.log( "Log base 2:" , log2Values); const log10Values = num2.map(num => Math.log10(Math.abs(num))); console.log( "Log base 10:" , log10Values); |
Cubic Roots: [ 2, -3, 2.5198420997897464 ] Log base 2: [ 3, 4.754887502163468, 4 ] Log base 10: [ 0.9030899869919435, 1.4313637641589874, 1.2041199826559248 ]
Method 15: New Number Methods
- Number.isInteger() Method: It checks if a value is an integer, returning true if it is, false otherwise.
- Number.isSafeInteger() Method: It verifies if a value is within the range of safe integers, preventing precision loss.
Example: In this example we are using the above-mentioned method.
Javascript
const num1 = 42; const num2 = 3.14; const num3 = 9007199254740992; // Largest safe integer console.log(Number.isInteger(num1)); console.log(Number.isInteger(num2)); console.log(Number.isSafeInteger(num1)); console.log(Number.isSafeInteger(num3)); |
true false true false
Method 16: New Global Methods
ES6 added 2 new global number methods:
- isFinite() Method: It checks if a value is a finite number, returning true for numbers, excluding NaN and Infinity.
- isNaN() Method: It checks if a value is Not-a-Number (NaN), returning true if it’s NaN, false otherwise.
Example: In this example we are using the above-mentioned methods.
Javascript
const var1 = 12; const var2 = "Beginner" ; const var3 = NaN; const var4 = Infinity; console.log(isFinite(var1)); console.log(isFinite(var2)); console.log(isNaN(var1)); console.log(isNaN(var2)); console.log(isNaN(var3)); console.log(isFinite(var3)); console.log(isFinite(var4)); |
true false false true true false false
Method 17: Object Entries
Object.entries() converts object properties to an array of [key, value] pairs, enabling iteration and manipulation of object contents.
Syntax:
Object.entries( obj )
Example: Here is the basic example of above-mentioned method.
Javascript
// creating an object constructor // and assigning values to it const obj = { 0: 'adam' , 1: 'billy' , 2: 'chris' }; // Displaying the enumerable property [key, value] // pairs of the object using object.entries() method console.log(Object.entries(obj)[1]); |
[ '1', 'billy' ]