The Spread Operator In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Spread Operator In JavaScript.
The Spread Operator In JavaScript
The spread operator in JavaScript is denoted by three dots (…) and can be used in several ways. One common use case is to spread the elements of an array into a new array or into the arguments of a function. For example:
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
Output
[1, 2, 3, 4, 5]
Another use case is to spread the properties of an object into a new object. For example:
let person = { name: 'John', age: 30 };
let newPerson = { ...person, location: 'New York' };
console.log(newPerson);
Output
{ name: ‘John’, age: 30, location: ‘New York’ }
It also can be used to copy an array or an object instead of referencing them
let originalArray = [1, 2, 3];
let copiedArray = [...originalArray];
console.log(copiedArray);
let originalObject = { name: 'John', age: 30 };
let copiedObject = { ...originalObject };
console.log(copiedObject);
Output
[1, 2, 3]
{ name: 'John', age: 30 }
It can also be used in function calls as a way to spread out the elements of an array as separate arguments
let numbers = [1, 2, 3];
console.log(Math.max(...numbers));
The spread operator can be used in many ways, but these are some common use cases.