Spread Operator in ES6

Spread Operator in ECMAScript 6

The term 'Spread Operator' can be defined as an operator that allows expending the array into separate elements. Three dots (…) isthe syntax of the Spread Operator.The Spread operator is used to expend the array in an area where zero or more than zero elements are expected. It provides the facility to access a parameter list from an array.

The Spread operator is the opposite of the rest parameter. Here is the syntax of the Spread operator.

Syntax of Spread Operator

var variable_name = [… value of variable]        // Syntax of spread Operator

Here are some uses of the Spread Operator in various cases.

Array Manipulation and a Spread Operator

Here, we will try to manipulate an array with Spread Operator.

How to create an Array in Literal form using a Spread operator?

Here, we create an array through the literal form. The spread operator provides us the facility to create or insert an array within an existing initialized array.

For Example

Let city = [‘Delhi’, ‘Noida’];
 Let newcity = […city, ‘Rampur’, ‘Jaipur’, ‘Agra’];
 Console.log(newcity); 

Output

After the execution of the code, we will get the following output-

[ ‘Delhi’, ‘Noida’, ‘Rampur’, ‘Jaipur’, ‘Agra’ ]

How to concatenate the Arrays using Spread Operator?

We can easily concatenate two or more arrays. In the below-given example, we will see the concatenation of two given array-

Let animal = [ ‘Cow’, ‘Cat’ ];
Let newanimal = […animal, ‘Dog’, ‘Goat’];
Console.log (newanimal); 

Output

After the execution of the code, we will get the following output-

[ ‘Cow’, ‘Cat’, ‘Dog’, ‘Goat’ ]

How to copy an array using Spread Operator?

In ECMAScript 6, we can easily copy an element of an array by using the Spread operator. Here, an example is given below-

Let country = [‘Pakistan’, ‘India’];
Let newcountry = […country];
Console.log (newcountry); 

Output

After the execution of the code, we will get the following output-

[  ‘Pakistan’, ‘India’ ] 

Note- If we copy an element of an array without using a Spread operator, then the element of an existing array will influence the main array.

When we copy the instance of the array without using Spread Operator, then the element of the existing array will not influence the main array.  

Here, we are going to take an example; how to copy an array with or without using the Spread Operator.

With using Spread Operator

let color = [‘Green’, ‘Red’];
let newcolor = […color];
newcolor.push (‘Blue’);
console.log (newcolor);
console.log (color); 

Output

After the execution of the code, we will get the following output-

Spread Operator in ECMAScript 6

Without using the Spread operator

let color = [‘Green’, ‘Red’];
let newcolor = color;
newcolor. Push (‘Blue’);
console.log (newcolor); console.log (color); 

Output

After the execution of the code, we will get the following output-

Spread Operator in ECMAScript 6

Note- The Spread Operator only copy the array into a new array, instead of values.

How to Spread a string using the Spread operator

The Spread operator allows the developer to spread a string or array expression extended to an area, where zero or more than zero arguments, functions are expected. It means if we use the spread operator to spread a string, then the compiler breaks the string elements in separate characters.

For Example

let arr = [‘R’, ‘ahu’, ‘l’];
 console.log (arr); 

In the example mentioned above, we have implemented a code using the spread operator. We have created an array “arr” and applied the spread operator on “ahu.” The operator expends each character of string separately.  

We will get the following output-

Spread Operator in ECMAScript 6

Rest Parameter in ECMAScript 6   

ECMAScript 6 provides a facility to use rest parameters. It helps to improve the capability to regulate the parameters. The term rest Parameter is defined as a parameter that allows the developer to manage different inputs as a parameter in a function. Itis an upgraded way to manage the function parameters. We can easily represent many arguments as an array. Before ECMAScript 6, the developer used the argument object of a function.

The rest parameter allows us to call a function via an argument. The syntax of the rest parameteris similar to the spread operator, but the working functionality is opposite to it. It is used with three dots (…).  The rest parameter has to be the final argument because it helps us to gather all the values of an array.

Syntax of Rest Parameter

function f1 (p, q…args)
 {
      // statements
 } 

Example of Rest Parameter

function sum (…theArgs)
 {
 return theArgs.reduce ((previous, current) => {
 return previous + current;
 });
 }
 Console,log (sum(2, 4, 6)); 

Output

Spread Operator in ECMAScript 6

In the above-given example code, all the function arguments will be stored in the parameter list. We will use the rest parameter (…) at the end of the parameter list. If we use it at any other place then, there should be chances of error occurrence.

For Example

function sum (a, …rest, b)
 {
                      // error
 } 

Difference between Rest Parameter and Argument Object

          Rest Parameter              Argument Object
The rest parameter is used to present one or more than one argument as an array. Argument Object is used to present function executing arguments.
It is also represented as an instance of an array.  The Argument object is not an array.
We can use foreach, map, sort, and pop method in the rest parameter. We cannot use these methods in Argument object.

Destructuring and Rest Parameter

The term Destructuring can be defined as a feature that is used to extract the value from the array and object. It helps us to separate the difficult structure into smooth parts. Destructuring is a JavaScript expression, used to unpack the value from the objects and arrays and draft them to the variables.  

The ECMAScript 6 supports only Array Destructuring. We can insert the elements of an existing array into a new array.

For Example

var countries = [“India”, “China”, “Dubai”, “Kenya”, “Nepal”, “Shri Lanka”];
 var 
 [a, b, …args]  = countries;                  // Destructuring Assignment 
 console.log (a);
 console.log (b);
 console.log (args); 

Output

Spread Operator in ECMAScript 6

In the above-given example, Destructuring feature with rest parameter separates the country names.

Dynamic Function with Rest parameter

The Dynamic function is a block statement of reusable, readable source code, which helps us to perform a particular task. The ECMAScript specification allows us to build a function via function constructor.

 Here is an example; How to use rest parameter with dynamic function?

let animal = new function (“…args”, “return args”)
                 console.log (animal(Dog, Cat, Horse)); 

Output

After the execution of the code, we will get the following output-

Spread Operator in ECMAScript 6

Related Topics

Loop Control Statement in ES6

Loop Control Statement in ECMAScript 6 The loop control statements can be defined as a set of conditions that control the execution of the loop. It executes the loop until the condition becomes false....

6 minutes read.

Object in ES6

Object in ES6 The term object can be defined as an instance that contains the group of key-value pairs. We can modify it using the life cycle of an object in...

6 minutes read.

Variables in ES6 | ECMAScript 6

Variables in ECMAScript 6 A Variable is a place in memory used to store a value. There are some rules for declaration of the variable- Variable Initialization Initialization is a process of locating and storing the initial...

4 minutes read.

Module in ES6

Module in ES6 In ES6, the modules can be defined as a small chunk of program code stored in a file. The modules are used to modularize the source code with...

6 minutes read.

Validation in ES6

Validation in ES6 The term validation can be defined as a mechanism to check the information given by the user is correct or not according to the requirements. If the data...

9 minutes read.

Events in ES6

Events in ES6 The events can be defined as the actions or the occurrence of an action that is perceived by the software. The event is used to handle the interaction between...

14 minutes read.

Page Redirect in ES6

Page Redirect in ES6 The term redirect can be defined as a process to send the user and search engine on a specified URL from the original page. “The page redirection is...

3 minutes read.

Number in ES6

Number in ES6 In ES6, we have various methods and properties to implement numeric functions such as floating-point, integers, date, etc. The numbers in ES6 enable us to work with number...

7 minutes read.

Immediately Invoked Function Expression ES6

Immediately Invoked Function Expression (IIFE) Immediately Invoked Function Expression (IIFE) is a JavaScript function used to ignore the variable hoisting from inside the code block. An IIFE is a function that runs...

3 minutes read.

ES6 | ECMAScript 6 Syntax

The term 'syntax' defines the grammar and spelling of any programming language. In Computer science, “Term syntax is a collection of some rules and regulations that determines the group of symbols used in...

8 minutes read.

Types of Inheritance in ES6

Types of Inheritance The term inheritance can be divided into following three parts- Single-level InheritanceMultiple InheritanceMulti-level Inheritance Single-level Inheritance The single-level inheritance can be defined as an inheritance in which the child class can...

5 minutes read.

Object Destructuring in ES6

Object Destructuring in ES6 The term destructuring is referred to as the breakdown of the complex entities into simpler parts. It works like array destructuring. In the array destructuring, the values...

3 minutes read.

Template Literals in ES6

Template Literals in ES6            ES6 introduced a new feature called template literals. It facilitates us to define a multiline string and executes the string interpolation. The template literals are referred to...

3 minutes read.

Boolean in ES6

Boolean in ES6 In ES6, the Boolean object is used to show two values either it may be true or false. In JavaScript, we can use the Boolean object as a...

4 minutes read.

String in ES6

String in ES6 The term string can be defined as an object used to represent the sequence of the characters. The string is widely used to store a text-based value like...

9 minutes read.

Map Object in ES 6

Map Object in ES 6 ES 6 introduced a new feature that is included in JavaScript. In the previous versions of ECMAScript, if we want to perform mapping on values and...

5 minutes read.

ES6 Tutorial

Introduction of ES6 The ECMAScript 6 is a scripting language specification institutionalized by ECMA International. ECMA, named in 1994, is an international organization, related to information and communication system. ECMA stands for “European Computer Manufacturers...

8 minutes read.

Operators in ES6 | ECMAScript 6

Operators in ECMAScript 6 The term Operator is refers to a symbol that is used to instruct the computer system to perform a specific operation. The ECMAScript 2015 supports a rich set of operators....

11 minutes read.

Arrow Function in ES6

Arrow Function in ES6  An Arrow function is a new concept recommended in ECMAScript 2015. It is also called “Fat Arrow Function.” It helps us to write the function more accurately. This function...

5 minutes read.

Loops in ES6 | ECMAScript 6

Loops in ECMAScript 6 A Loop statement can be defined as a group of instructions that are always repeated. In the computer programming language, the loops help us to execute a collection of instructions...

8 minutes read.