JavaScript copying (by value and by reference)
differences between each kind of copying
In JavaScript, "copying" could mean two different things:
by value (original doesn't change if copy changes)
by reference (original does change if copy changes)
Copying by value
When we copy some primitives, we copy by value, so that the original does not change if the copy changes:
Note that despite setting y
equal to x
, then changing y
's value - the value of x
does not change!
This happens with:
a
Number
a
String
a
Boolean
a
null
an
undefined
a
Symbol
Copying by reference
However, with:
an
Object
a
function
an
Array
...we copy by reference:
Notice how changing object2
's property also changed object1
's property automatically!
Last updated