The spread syntax, or …
in JavaScript, is a new addition to the set of operators in JavaScript ES6. It takes in an iterable, like an array, and expands it into individual elements.
Three Dots (...) in JavaScript Explained
The three dots ...
in JavaScript is known as the spread syntax, and it is commonly used to make shallow copies of JavaScript objects. It does this by taking in an iterable and expanding it into its individual elements.
The spread syntax is commonly used to make shallow copies of JavaScript objects. Using this operator makes the code concise and enhances its readability.
Three Dots (...) Operator Syntax in JavaScript
The three dots operator or spread syntax in JavaScript is denoted by three dots: …
.
let array = [...value]
Three Dots (…) Operator Examples in JavaScript
Since the array data structure is widely used, it will be considered in all the subsequent examples.
1. Copying an Array
The array2
has the elements of array1
copied into it. Any changes made to array1 will not be reflected in array2 and vice versa.
If the simple assignment operator had been used, then array2
would have been assigned a reference to array1
. The changes made in one array would be reflected in the other array, which in most cases is undesirable.
let array1 = ['h', 'e', 'l', 'l', 'o'];
let array2 = [...array1];
console.log(array2);
['h', 'e', 'l', 'l', 'o'] // output
2. Inserting the Elements of One Array Into Another
The spread syntax can be used to append one array after any element of the second array. In other words, there is no limitation that desserts
can only be appended at the beginning of the end of the desserts1
array.
let desserts = ['cake', 'cookie', 'donut'];
let desserts1 = ['icecream', 'flan', 'frozen yoghurt', ...desserts];
console.log(desserts);
//Appending baked_desserts after flan
let desserts2 = ['icecream', 'flan', ...desserts, 'frozen yoghurt'];
console.log(desserts2);
// output
[ 'cake', 'cookie', 'donut' ]
[ 'icecream', 'flan', 'cake', 'cookie', 'donut', 'frozen yoghurt' ]
3. Array to Arguments
function multiply(number1, number2, number3) {
console.log(number1 * number2 * number3);
}
let numbers = [1,2,3];
multiply(...numbers);
Instead of having to pass each element like numbers[0]
, numbers[1]
and so on, the spread syntax allows array elements to be passed in as individual arguments.
//Passing elements of the array as arguments to the Math Object
let numbers = [1,2,300,-1,0,-100];
console.log(Math.min(...numbers));
The Math
object of Javascript doesn’t take in a single array as an argument but with the spread syntax, the array is expanded into a number of arguments with just one line of code.