Learning ES6 JavaScript Spread Operator
JavaScript spread operator (...) is used to expand the values of an iterable ( usually an array or an object) so that you can pass those values as arguments of a function. For example, let’s say you have a function that calculates the sum of three numbers:
function sumThree(a, b, c){
return a+b+c;
}
Next, you want to pass an array of three numbers into the function. You can use the spread operator on the function:
let scores = [7, 9, 7];
let summedNumber = sumThree(...scores);
// The same as sumThree(7, 9, 7);
console.log(summedNumber);
// output is 23
You can merge two or more arrays using spread operator:
let firstArray = [4, 5];
let secondArray = [9, 10];
let mergedArray = [...firstArray, ...secondArray];
// mergedArray is [4, 5, 9, 10]
You can also use this merging technique to objects:
let firstObject = { name: "Jack" };
let secondObject = { age: 19 };
let mergedObject = {...firstObject, ...secondObject};
// mergedObject is { name: "Jack", age: 19 }
But the spread operator can’t be used to pass object properties into a function:
let user = {
name: "Jack",
age: 27
};
function greetings(name, age){
console.log(`Hello, my name is ${name} and I'm ${age} years old`);
}
greetings(...user);
// Will cause an error
// Uncaught TypeError: Found non-callable @@iterator at <anonymous>:1:1
Spread operator use cases
The spread operator can be used on both Math.min and Math.max method to find the value inside an array.
It also can be used on React to pass props between components.
More JavaScript tutorials
See allJavaScript
Sort Keys in Map Using JavaScript
Dec 11, 2023
JavaScript
Get Element by Data Attribute Using JavaScript
Dec 8, 2023
JavaScript
Convert Milliseconds to Hours Minutes Seconds in JavaScript
Dec 6, 2023
JavaScript
JavaScript Get the Index of Max Value in Array
Nov 16, 2023
JavaScript
JavaScript Check if Value is an Object
Nov 15, 2023