Spread operator denotes as ... triple dot
Spread operator converts array into single entity.
Can use spread operator to create, copy new array with the inclusion of existing elements.
Spread Operator with an Array
Converting each element of an array into a single entity value.
const number = [1,2,3];
const sum = (a, b, c) => {
return a + b + c;
}
console.log(sum(...number))
//Output : 6
Can add element before and after of the spread operator, to make new array.
console.log([0, ...number, 4])
// Output: [0,1,2,3,4]
Spread operator with an object
const profile = {
name: "John"
}
const updatedProfile = {...profile, email: "test@gmail.com"}
console.log(updatedProfile)
//Output : {name: 'John', email: 'test@gmail.com'}
There is a difference between spread operator and Object.assign, in context of an object.
Object.assign can mutate the value of the same Object.
Where as spread operator just clone to another object while creating with new properties.
Using Object.assign, the original object has changes, it added new property age
const user = {
name: "John"
}
Object.assign(user, {age: 10});
console.log(user)
//Output : {name: 'John', age: 10}

0 Comments