Psst: have a look at the JavaScript Console 🌹
In JavaScript, Primitive Types such as undefined, null, string, number, boolean and symbol are passed by value.
When the variable name is assigned, a space in memory with an address of 0x001 is reserved to store that value. The variable name then points to that address.
The variable name2 is then set to equal name. A new space in memory, with a new address 0x002 is alocated and stores a copy of the value stored in the address name points to.
So, whenever we want to modify the value of name, the value stored by name2 won't be changed, since its a copy, stored in a different location.
Objects in JavaScript are passed by reference. When more than one variable is set to store either an object, array or function those variables will point to the same alocated space in memory.
When animals is set to store an array, memory is alocated and an address is associated to that variable. Then animals2 is set to equal animals. Since animals stores an array, instead of creating a copy of that array and a new address in memory, animals2 is simply pointed to the same object in the existing address. That way any changes made to animals2 will reflect on animals, because they point to the same location.
Same behaviour for objects:
Since a simple assignment is not enough to produce a copy of an object, that can be achieved by other approaches:
Arrays slice()Changes will affect only the object modified:
It's important to note that those methods are just one level deep. For deep clones there is a frowned upon method. Use carefully.
References
D’Ascoli, C. (2017, July 07). Javascript Passing by Value vs. Reference Explained in Plain English. Retrieved February 09, 2018, from https://codeburst.io/javascript-passing-by-value-vs-reference-explained-in-plain-english-8d00fd06a47c