Primary Value and Reference Value

Tram Ho

In this article, I would like to introduce to you the concept of Variable and its operations in Javascript

1. Basics

In Javascript , variable are stored by two types of values: Primitive Value and Reference Value

Primitive Value (6): null , undefined , number , string , boolean , symbol

Reference Value (1): object

Looking here, you will see questions, NaN and Array . These two guys often meet but do not see any classification.

Primitive Value : NaN has a type of number

Refernce Value : array has an object type

You can verify by using the typeof statement

2. Copying Primitive Value

When you specify a variable a stores Primitive Value into a variable b . Value created in variable a will create and copy to variable b

See the following example:

  1. Define a variable a and initialize its value to 10

  1. Define a variable b and initialize its value by a

  1. Specify varaible b with a different value

variable a and variable b not related to each other. So when you change the value of one guy, the other guy won’t change

3. Copying reference values

When you specify a Reference value from a variable to a variable another value stored in the variable is copied to the location of new developments

The difference is that the value is stored in both variable with the same address. Both varaible now refer to the same object

See the following example:

Declare variable x hold value as an object with name attribute:

Declare the variable y = x

Now both x and y refer to the same object Next we change the value of x , y will be changed accordingly

4. Some common examples

1. Reference Value in the case of parameters passed to the function

In this case, if:

  • Reference Value is a parameter passed to the function
  • In the function we want to transform the data

=> Here you need to consider when transforming the data itself as it changes the original value

2. How to overcome guy on how?

If you want to fix this guy. You use some functions to create new data. Let’s call it clonedData. We can use Object.assign , Spread Operation (ES6)

For Array you can refer here: https://futurestud.io/tutorials/clone-copy-an-array-in-javascript-and-node-js

Share the news now

Source : Viblo