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

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.

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...

5 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.

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.

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.

Array Methods in ES6

Array Methods in ES 6 ES 6 introduced the various new methods such as Array,from(), Array,of(). Here, we have the various array methods used in JavaScript, they are given below in the table...

10 minutes read.

Dialog box in ES6

Dialog box in ES6 A dialog box can be defined as a regular type of window in the Graphical User Interface (GUI) of the operating system. It is also spelled as...

5 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.

Array in ES6

Array in ES6 The array can be defined as an object that is used to display the set of homogenous type of elements in ECMAScript 6. The array provides the facility to store...

5 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.

Environment Set up in ES6

Environment Set up in ES6 JavaScript is a portable language. It can execute on any browser or any host, and any operating system. Before the use of JavaScript, we need to...

5 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.

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.

Promises in ES6

Promises in ES6 A promise is used to represent some aspects that are finally fulfilled. It can also be resolved or discarded according to the operational output. In ES6, a promise...

8 minutes read.

Functions in ES6 | ECMAScript 6

Functions in ECMAScript 6 In ECMAScript programming language, the term ‘function’ can be defined as a collection or group of input statements, used to perform particular computational calculations and generate the output...

9 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.

Array Destructuring in ES6

Array Destructuring in ES6 The term ‘Destructuring’ is defined as dividing the complicated data structure into easier modules. The Destructuring syntax helps to extract the small segments from an array and the objects....

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.

Animation in ES6

Animation in ES6 In JavaScript, the animation feature is used to manage the aspect that the CSS (Cascading Style Sheet) can’t. JavaScript provides various new elements that help us to construct...

8 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.