JavaScript - eodeluga/dev-notes GitHub Wiki

JavaScript

Objects are assigned / passed by reference

If you assign an object to a variable (a), then assign a to a new variable (b), any change made to b affects a too.

const a = {
    one: 1,
    two: 2,
};

const b = a;

b.one = 4;

console.log(a.one); // 4

You can make changes to an object by cloning it and having those changes reflected only in the new object using Object.assign()

const changeObj = (obj, prop, value) => Object.assign({}, obj, { [prop]: value });
const c = changeObj(a, 'one', 30);

console.log(a.one); // 4
console.log(c.one); // 30