Skip to content

Instantly share code, notes, and snippets.

Created Dec 31, 2018
What would you like to do?
Avoid mutation in js
In javascript array and object are mutable so to avoid mutation we need to use Spread Operator.
// To add new element ('four') to an array.
const arr1 = [1,2,3];
const fourth = 'four';
const arr2 = [...arr1, fourth];
// Output for arr2: [1, 2, 3, "four"]
// Output for arr1: [1, 2, 3]
// To add new key value pair (d: "D") to an object.
const obj1 = {a: "A", b: "B", c: "C"};
const obj2 = {...obj1, ...{d: "D"}}
// Output for obj2: {a: "A", b: "B", c: "C", d: "D"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment