Skip to content

Instantly share code, notes, and snippets.

@sureshshrestha
Created December 31, 2018 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sureshshrestha/902c24ea6924f30e0ce3513f1dad3cdf to your computer and use it in GitHub Desktop.
Save sureshshrestha/902c24ea6924f30e0ce3513f1dad3cdf to your computer and use it in GitHub Desktop.
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