-
-
Save sureshshrestha/902c24ea6924f30e0ce3513f1dad3cdf to your computer and use it in GitHub Desktop.
Avoid mutation in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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