![]() |
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 OperatorThe 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. Syntaxlet varName = [ ...value ];
Example 1: In this example, the Spread Operator combines arrays arr1 and arr2 effectively concatenating their elements into the resulting array. Javascript
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
Output
{ name: 'Amit', age: 22, city: 'Uttarakhand' } Rest ParameterThe 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 Example 1: In this example, the sumFunction accepts any number of arguments and calculates their sum using the rest parameter. Javascript
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
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. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |