DEV Community

Cover image for Javascript academy #1: Primitive value vs reference value
Code Oz
Code Oz

Posted on • Updated on

Javascript academy #1: Primitive value vs reference value

Welcome to this new academy! In this I will NOT explain you javascript from scratch, the aim of this javascript academy is to explain you some concept in javascript that will help you to understand javascript engine!

Today I will show you the difference between primitive value & reference value.

Primitive value

Primitive value are string, number, boolean, null, undefined and symbols.

Reference value

All others things like plain object {}, array, Map, etc...

How data is stored?

For Primitive value the value is store on the stack, in other word, in the current context!

For Reference value the value is store in the heap, it's a big storage that keep all objects and each object has it's own adress! (Like house in a village, each house has its own adress)

Image description

So in order to get the object through the Heap you need to use the adress of this object!

Image description

Fortunately you don't need to manage the adress yourself!

Declaration of variable

For Primitive value the variable store the value. So you manipulate the actual value stored in this variable.

let toto = 5
toto = 6
console.log(toto) // 6
Enter fullscreen mode Exit fullscreen mode

Image description

For Reference value unlike primitive value when you manipulate an object you work on the reference of that object! So you store the reference of the object in the variable.

let toto = {}
toto.a = 'hello'
console.log(toto) // { a: 'hello' }
Enter fullscreen mode Exit fullscreen mode

Image description

Copy a value

For Primitive value when you assign a variable that store primitive value it will copy the value into a new variable.

So if you modify the value into a variable, the other variable value will be not changed.

let a = 55
let b = a

a = 100
console.log(a) // 100
console.log(b) // 55
Enter fullscreen mode Exit fullscreen mode

Image description

For Reference value when you assign a variable that store reference value it will copy the reference of this object into a new variable.

So if you modify the value into a variable, the other variable value will change! Since both variable share the same reference!

let a = {}
let b = a

a.toto = 'hello'
console.log(b) // { toto: 'hello' }
Enter fullscreen mode Exit fullscreen mode

Image description

Working with function parameters

For Primitive value when you pass a variable that contains a primitive value as arguments of your function, it will copy the value of this variable.

So if you edit this value into the function, it will not change the value in the original variable!

let a = 55

const foo = function (arg) {
   arg = 100
   console.log(arg) // 100
}
foo(a)
console.log(a) // 55
Enter fullscreen mode Exit fullscreen mode

For Reference value when you pass a variable that contains a reference value as arguments of your function, it will copy the reference of this variable.

So if you edit this value into the function, it will change the value in the original variable!

let a = { toto: 'hello' }

const foo = function (arg) {
   arg.toto = 'changed'
   console.log(arg) // { toto: 'changed' }
}
foo(a)
console.log(a) // { toto: 'changed' }
Enter fullscreen mode Exit fullscreen mode

As you can see when you are working with reference value you can edit other variable that are sharing this reference value!


I hope you like this reading!

🎁 You can get my new book Underrated skills in javascript, make the difference for FREE if you follow me on Twitter and send message to me 😁 and SAVE 19$ 💵💵

Or get it HERE

🇫🇷🥖 For french developper you can check my YoutubeChannel

🎁 MY NEWSLETTER

☕️ You can SUPPORT MY WORKS 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : https://twitter.com/code__oz

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!

Top comments (10)

Collapse
 
akashkava profile image
Akash Kava

In JavaScript, primitive means immutable, they don’t live on stack. String is never put on stack. In V8 there are objects such as V8Number etc which are primitive but do not live on stack.

V8 tries to optimize code by using short circuit variables on stack such as creating two numbers and adding them. However if number comes as an input it will be on heap.

In high level languages, unless they are strictly typed, it is impossible to put primitives on stack as there would be too much boxing required which will make code slower to generate and execute.

Collapse
 
codeoz profile image
Code Oz

Primitive value are immutable as you said, the variable will store this value inside it, but this variable live in the stack (variable that store primitive or reference value, but for reference value, the variable store the reference of the object in the stack but the object is store into the Heap, and you get the object thanks to this reference into the Heap).

I don't understand when you speak about V8Number.

If you want to check some others source:

Collapse
 
akashkava profile image
Akash Kava • Edited

In the same Stackoverflow link given in the last this is the line.

Well for starters we're talking about JavaScript, and JavaScript doesn't have a stack or a heap. It's a dynamic language and all the variables in JavaScript are dynamic. To explain the difference I'll compare it to C....

I have integrated V8 for Android at github.com/web-atoms/xamarin-v8 and I can guarantee, that nothing except small integer (31 bits, one bit to differentiate heap allocated number) lives in the stack, V8Number is the exact class which is allocated on the heap which stores the value, all JavaScript values are on heap and they are all derived from V8Value class, please refer to the source code of V8.

Now, v8 analyzes source code and does some shortcut, like adding two numbers,

function add(a) {
   var c = 2;
   return a + c;
}
Enter fullscreen mode Exit fullscreen mode

In Above function, a is unknown, so it is of type V8Value in C++. However, V8 sees that we are adding literal 2 which is kept in variable c, so V8 intelligently puts 2 in stack and then combines it with a. As long as compiler can track the type, it can keep it on stack, otherwise it needs to create reference. As everything passed as an argument to other method in C++ are handled by references.

So only for certain operations V8 puts things on stack, otherwise everything lives in heap, when you call a method add(2, 4) , all though you know that you are passing 2 and 4 but function doesn't , everything is dynamic. So compiler has to allocate V8Number, and pass reference to add method.

To understand how complex it is to put primitives on stack, try creating a small javascript engine and you will see how it is possible and how it is complex enough to not do it.

Collapse
 
vonmehdi profile image
EL MEHDI ESSAADI

I want to ask u someting, how to delete a object? to make his space free to use again.

Collapse
 
codeoz profile image
Code Oz

I will make another topic but shortly, the memory of the Heap (where object are living and stored) is handled by garbage collector.

When you create an object you store the reference in this variable, but if you change this variable, you lost the reference into this object, so there is no access for it! And the garbage collector will delete this object.

A quick example

let a = { toto: 'hello' }
let b = a 
// Both variable store the reference of { toto: 'hello' }

a = 55
// b is the only variable that keep the reference of the object

b = 60
// There is no variable that keep this reference, so the Garbage collector will delete the object

Enter fullscreen mode Exit fullscreen mode
Collapse
 
vonmehdi profile image
EL MEHDI ESSAADI

Thanks I understand it, js is really a smart language.

Collapse
 
vonmehdi profile image
EL MEHDI ESSAADI

Thanks, thats what I was loking for.

Collapse
 
codeoz profile image
Code Oz

you are welcome! If you need more details you can check this javascript.info/garbage-collection !

Collapse
 
vonmehdi profile image
EL MEHDI ESSAADI

I read it, I understood the concept of reachability, if there is no reference or chain of references to an object it will be delete.
Thanks agian .

Thread Thread
 
codeoz profile image
Code Oz

Happy to help you 😊

Some comments have been hidden by the post's author - find out more