Skip to content

Instantly share code, notes, and snippets.

@mattjstar
Created October 27, 2016 19:25
Show Gist options
  • Save mattjstar/2459fa6cf4fe1a4d1add20df93e89a31 to your computer and use it in GitHub Desktop.
Save mattjstar/2459fa6cf4fe1a4d1add20df93e89a31 to your computer and use it in GitHub Desktop.
Object Assignment in JS
const arr1 = [1,2,3];
console.log("arr1 BEFORE PUSH: ", arr1);
arr1.push(4);
console.log("arr2 AFTER PUSH", arr1);
const a1 = [1,2,3];
console.log("a1 BEFORE CONCAT: ", a1);
const a2 = a1.concat([4,5,6]); // [ ...a1, 4,5,6 ]
console.log("a1 AFTER CONCAT: ", a1);
console.log("a2 AFTER CONCAT: ", a2);
// same as arr1.concat, using the spread operator (put all elements in arr1, and continue with 4, 5, 6 after that, producing a new array)
// Similar syntax for objects (Object.assign() or extend).
// *** Note objects at the end of the list take precednece, so if you have 2 objects with the same key the second takes precendence.
const obj1 = { a: 'a' };
console.log("obj1 BEFORE MUTATION", obj1);
Object.assign(obj1, { b: 'b' });
console.log("obj1 AFTER MUTATION", obj1);
// NOT MUTATED (only object that gets mutated by Object.assign is the left most object):
// Don't forget to add the first object
const o1 = { a: 'a' };
console.log("o1 BEFORE ASSIGN", o1);
const o2 = Object.assign(
{},
obj1,
{ b: 'b' }
);
console.log("o1 AFTER ASSIGN", o1);
console.log("o2 AFTER ASSIGN", o2);
// The babel ES7 spread operator way:
const ob1 = { a: 'a' };
const ob2 = {
...ob1,
b: 'b',
c: 'c',
};
console.log('spread ob1', ob1);
console.log('spread ob2', ob2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment