paint-brush
JavaScript Reference and Copy Variablesby@vcapretz
43,024 reads
43,024 reads

JavaScript Reference and Copy Variables

by Vítor CapretzFebruary 16th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Each programming language has its own peculiarities (and JavaScript has a lot), and today I’m going to talk about variables that are assigned by reference and the ones that are assigned by copy methods.

Company Mentioned

Mention Thumbnail
featured image - JavaScript Reference and Copy Variables
Vítor Capretz HackerNoon profile picture

Each programming language has its own peculiarities (and JavaScript has a lot), and today I’m going to talk about variables that are assigned by reference and the ones that are assigned by copy methods.

Primitive vs Compound Values

First of all, let’s see each type of value in JavaScript:

Primitive

  • null, undefined
  • String
  • Number
  • Boolean

Compound

  • Object
  • Array
  • Function

So, technically, Primitive values are always Pass-by-value (copied) and Compound values are Pass-by-reference. Here is an example:

But, for Compound values, it would be something like this:

And there’s always the exceptions…

Wait… Why are the values different now? Weren’t Objects and Arrays supposed to be referencing each other?

Well, what happens is that JavaScript is actually passing a reference by value and if you change one property of an Object or an Array, you are not changing the reference at all.

When you assign a hole new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array!

How to fix this?

Let’s say you want to update the properties of your Object and mess up with your Array without worrying about the original value itself.

To fix this, make a copy instead! Here is the code (be aware of the methods available just for ES6 version):

Now you don’t need to worry about the original values! Use this solution whenever you want to copy two original values and later on they can differ from each other.

That’s it!

I hope that this post might by as useful to you guys as it was to me when I learned about it! I’m continuing my journey of learning more JavaScript and writing about it, so don’t forget to follow me here on Medium and on Twitter!

And of course, if you liked it give your “Recommend” by clicking in the heart button and comment below something you would like to learn about JavaScript and/or your feedback!