Open In App

JavaScript Ellipsis

Last Updated : 20 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Ellipsis (also known as the spread/rest operator) is represented by three dots (…). It is used for various tasks, such as spreading elements of an array into individual values or collecting multiple values into an array or object. It simplifies data manipulation and function parameter handling.

We will explore the basic implementation of the Spread/Rest operator with the help of examples.

Spread Operator

The JavaScript Spread Operator (three dots …) is used to expand elements from arrays, objects, or function arguments and spread them into a new context or structure.

Syntax

let varName = [ ...value ]; 

 

Example 1: In this example, the Spread Operator combines arrays arr1 and arr2 effectively concatenating their elements into the resulting array.

Javascript




// Concatinating two arrays
// using Spread Operator
let arr1 = [ 4, 5 ];
let arr2 = [ 8, 9, 10 ]
  
arr = [ ...arr1, ...arr2 ];
console.log(arr);


Output

[ 4, 5, 8, 9, 10 ]

Example 2: In this example, the Spread Operator is used to clone an object (originalObject) and add/modify properties to create a new object. Here, we create a new object copiedObject by cloning obj1 and adding the city property.

Javascript




const obj1 = { name: "Amit", age: 22 };
const newObject = { ...obj1, city: "Uttarakhand" };
  
console.log(newObject);


Output

{ name: 'Amit', age: 22, city: 'Uttarakhand' }

Rest Parameter

The JavaScript Rest Parameter (…) allows functions to accept an arbitrary number of arguments as an array, simplifying the handling of variable-length parameter lists.

Syntax

// Triple Dots (...) is the Rest Parameter
function functionname( ...parameters ) {
statement;
};

Example 1: In this example, the sumFunction accepts any number of arguments and calculates their sum using the rest parameter.

Javascript




function sumFunction(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}
  
console.log(sumFunction(1, 2, 3, 4, 5));


Output

15

Example 2: In this example, we perform array destructuring with the rest parameter to assign the first as 1, the second as 2, and the rest as [3, 4, 5] from the given array. It then prints these values.

Javascript




let [first, second, ...rest] = [1, 2, 3, 4, 5];
  
// Output: 1
console.log(first);
  
// Output: 2
console.log(second);
  
// Output: [3, 4, 5]
console.log(rest);


Output

1
2
[ 3, 4, 5 ]

Both the Spread Operator & the Rest Operator can easily be distinguished. If the three dots (…) are specified at the end of function parameters, which defines the Rest parameters, which gathers all the other lists of arguments into an array, whereas, if three dots (…) occur in a function call, then it defines the Spread operator, that will expands an array into a list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads