r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

6

u/IamAPengling May 28 '19

JavaScript variables are passed by value, but objects are passed by reference.

This means if you do obj1 = obj2, there is a high possibility that if your change the value of any variable inside obj1, it may change inside obj2 as well and vice versa.

The correct way to fix this is Object.assign(obj1,obj2).

4

u/[deleted] May 28 '19

This is poorly written.

If obj2 is an object or an array, changes in obj1 will change obj2 since obj1 will just be a reference to obj2. Any primitive value such as numbers, strings, and booleans are not passed by reference.

Object.assign does not assign the obj2 to obj1, but assigns all properties of obj2 to obj1. This is very different than obj1 = obj2 since obj1 must be an existing object and will have references to any object in obj2 as well as copies of primitives, AND whatever was in the original object that hadn’t been assigned from object 2.

3

u/tomius May 28 '19

You're right. It should be

const obj2 = Object.assign({}, obj1)

→ More replies (3)