JavaScript Spread Syntax (...)
Last Updated :
12 Apr, 2023
The spread syntax is used for expanding an iterable in places where many arguments or elements are expected. It also allows us the privilege to obtain a list of parameters from an array. The spread syntax was introduced in ES6 JavaScript. The spread syntax lists the properties of an object in an object literal and adds the key-value pairs to the newly generated object.
The spread syntax is different from the rest operator as the spread operator expands any iterable into a list of elements whereas the rest operator is used to add other information supplied.
The spread syntax can be used in three places:
Syntax:
// spread in function call
function(...obj){ // function body }
// spread in array literal
let nameOfVar = [...valueToSpread];
// spread in object literal
let spreadObj = {...obj}
Parameter:
- valueToSpread: The iterable that is to be assigned to the new variable is mentioned here. It can be an Array or a String.
Return Type: It returns the argument list of the object passed after three dots.
Spread syntax in Function arguments: The spread syntax can be used to pass values in a function. It is helpful in situations where we do not know the exact number of arguments that are to be passed. This helps to replace the inbuilt apply() method
Example 1: In this example, we will use the spread syntax in the function arguments
JavaScript
function multiply(...objects){
let ans = 1;
for(let i = 0; i < objects.length; i++){
ans *= objects[i];
}
console.log(ans);
}
multiply(8, 2);
multiply(9, 4, 6);
Output:
16
216
Spread syntax in Array literal: The spread syntax is very useful in array literal as it can be used for cloning an array. If we do cloning with inbuilt array methods or assignment operator it can cause some issues as the inbuilt method copy the reference(deep copy) of the array and any changes made in the new array will reflect in the old array.
Example 2: In this example, we will use the spread syntax in Array literal.
JavaScript
let alpha1 = ['a', 'b', 'c'];
let alpha2 = ['d', 'e', 'f'];
// Concatenating using three dots
alpha1 = [...alpha1, ...alpha2];
console.log(alpha1);
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Spread syntax in object literal: The problem of deep copy also arises in cloning an object using the Assignment operator('='). So, spread syntax helps to overcome this problem and create a new object with shallow copy i.e. changes made in the new object will not reflect in the old object.
Example 3: In this example, we will use the spread syntax in object literal.
JavaScript
let obj1 = {
name: 'Sham',
age: 20,
skill: "Java"
}
let obj2 = {...obj1};
console.log(obj2);
Output:
{name: 'Sham', age: 20, skill: 'Java'}
Apart from these examples, we can also use the spread operator to pass arguments in constructors. This is useful when we have data in the format of an array that cannot be directly passed as an array so the spread operator converts it into a list of parameters and the data is accepted.
Example: In this example, we will pass the date as an array and create a new date object.
JavaScript
let date = [2000, 6, 15];
let newDate = new Date(...date);
console.log(newDate);
Output:
Sat Jul 15 2000 00:00:00 GMT+0530 (India Standard Time)
Errors and Exceptions: It must be understood that only those objects can be spread which are iterable. For eg. spreading a plain object will throw an error that the object is not iterable.
Example:
JavaScript
const demoObj = {
name: 'Ram',
age: '22'
};
const cloneObj = [...demoObj];
Output:
We have a complete list of Javascript ES6 features, to check those please go through this Introduction to ES6 article.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic Guide to JavaScript.
Similar Reads
JavaScript Syntax
JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.Syntaxconsole.log("Basic Print method in JavaScript");Ja
6 min read
JavaScript Spread Operator
The Spread operator (represented as three dots or ...) is used on iterables like array and string, or properties of Objects. to expand wherever zero or more elements are required top be copied or assigned. Its primary use case is with arrays, especially when expecting multiple values. The syntax of
4 min read
JavaScript Statements
JavaScript statements are programming instructions that a computer executes. A computer program is essentially a list of these "instructions" designed to perform tasks. In a programming language, such instructions are called statements.Types of Statements1. Variable Declarations (var, let, const)In
4 min read
JavaScript String Operators
JavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
JavaScript Template Literals
Template literals are string literals that allow embedded expressions (variables) into your code. They are enclosed by backticks (`) instead of single (') or double (") quotes.It was introduced in ES6, which provides a more flexible and readable way to work with strings. Unlike traditional string co
5 min read
What does '...' mean in JavaScript?
The '...' (or 3 dot symbol) in JavaScript is known as the Spread operator or Rest operator based on the usage. This syntax is used to expand the iterable into individual elements such as arrays, objects, etc.Syntax for Spread Operatorcosnt a1 = [ 10, 20, 30, 40 ];const a2 = [ ...a1, 50]; // Extracti
4 min read
Spread vs Rest operator in JavaScript ES6
Rest and spread operators may appear similar in notation, but they serve distinct purposes in JavaScript, which can sometimes lead to confusion. Let's delve into their differences and how each is used. Rest and spread operators are both introduced in javascript ES6. Rest OperatorThe rest operator is
2 min read
Map to Array in JavaScript
In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
3 min read
JavaScript Assignment Operators
Assignment operators are used to assign values to variables in JavaScript.JavaScript// Lets take some variables x = 10 y = 20 x = y // Here, x is equal to 20 console.log(x); console.log(y); Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in the table with the des
6 min read
What are these triple dots (...) in JavaScript ?
In JavaScript, there are multiple ways in which we can assign the value of one object to another. Sometimes we do not know the exact number of arguments that are to be assigned. In this case, the triple dots are used. The triple dots are known as the spread operator, which takes an iterable(array,
4 min read