40

I read a book called "Professional Javascript for web developer" and it says: "Variable is assigned by Reference value or Primitive Value. Reference values are objects stored in memory". And then it says nothing about how Primitive value is stored. So I guess it isn't stored in memory. Based on that, when I have a script like this:

var foo = 123;

How does Javascript remember the foo variable for later use?

BryanH
  • 5,460
  • 3
  • 33
  • 47
Lac Viet
  • 630
  • 1
  • 7
  • 10
  • 5
    Sounds like a rubbish book. Of course 'foo' is stored in memory. I guess it was trying to say that reference values are *objects* stored in memory, but primitive types are *values* stored in memory? – MadSkunk Nov 07 '12 at 09:23
  • 1
    @LacViet - Please read my answer. I believe it answers your question more accurately: http://stackoverflow.com/a/13268731/783743 – Aadit M Shah Nov 07 '12 at 11:29

7 Answers7

108

Okay, imagine your variable to be a piece of paper - a sticky note.

Note 1: A variable is a sticky note.

Now, a sticky note is very small. You can only write a little bit of information on it. If you want to write more information you need more sticky notes, but that's not a problem. Imagine you have an endless supply of sticky notes.

Note 2: You have an endless supply of sticky notes, which store small amounts of information.

Great, what can you write on your sticky note? I can write:

  1. Yes or no (a boolean).
  2. My age (a number).
  3. My name (a string).
  4. Nothing at all (undefined).
  5. A doodle or anything else which means nothing to me at all (null).

So we can write simple things (let's be condescending and call them primitive things) on our sticky notes.

Note 3: You can write primitive things on your sticky notes.

So say I write 30 on a sticky note to remind myself to buy 30 slices of cheese for the little party I'm throwing at my place tonight (I have very few friends).

When I go to put my sticky note on the fridge I see that my wife has put another sticky note on the fridge which also says 30 (to remind me that her birthday is on the 30th of this month).

Q: Do both the sticky notes convey the same information?

A: Yes, they both say 30. We don't know if it's 30 slices of cheese or the 30th day of the month, and frankly, we don't care. For a person who didn't know any better, it's all the same.

var slicesOfCheese = 30;
var wifesBirthdate = 30;

alert(slicesOfCheese === wifesBirthdate); // true

Note 4: Two sticky notes which have the same thing written on them convey the same information, even though they are two different sticky notes.

I'm really excited about tonight - hanging out with old friends, having a great time. Then some of my friends call me and say that they won't be able to make it to the party.

So I go to my fridge and erase the 30 on my sticky note (not my wife's sticky note - that would make her very angry) and make it a 20.

Note 5: You can erase what's written on a sticky note and write something else.

Q: That's all good and fine, but what if my wife wanted to make write a list of groceries for me to pick up while I was out to get some cheese. Would she need to write a sticky note for every item?

A: No, she would take a long list of paper and write the list of groceries on that paper. Then she would write a sticky note telling me where to find the list of groceries.

So what's happening here?

  1. A list of groceries is obviously not simple (erm... primitive) data.
  2. My wife wrote it on a longer piece of paper.
  3. She wrote where to find it in a sticky note.

Honey, the list of groceries is under your keyboard.

To recap:

  1. The actual object (the list of groceries) is under my keyboard.
  2. The sticky note tells me where to find it (the address of the object).

Note 6: Reference values are references to objects (addresses where they will be found).

Q: How do we know when two sticky notes say the same thing? Say my wife made another grocery list in case I misplaced the first, and wrote another sticky note for it. Both the lists say the same thing, but do the sticky notes say the same thing?

A: No. The first sticky note tells us where to find the first list. The second one tells us where to find the second list. It doesn't matter whether the two lists say the same thing. They are two different lists.

var groceryList1 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];
var groceryList2 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];

alert(groceryList1 === groceryList2); // false

Note 7: Two sticky notes convey the same information only if they refer to the same object.

This means if my wife made two sticky notes reminding me where the grocery list is, then the two sticky notes contain the same information. So this:

Honey, the list of groceries is under your keyboard.

Contains the same information as:

Don't forget that the list of groceries is under your keyboard.

In programming terms:

var groceryList1 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];
var groceryList2 = groceryList1;

alert(groceryList1 === groceryList2); // true

So that's all that you need to know about primitives and references in JavaScript. No need to get into things like heap and dynamic memory allocation. That's important if you're programming in C/C++.

Edit 1: Oh, and the important thing is that when you pass variables around you're essentially passing primitive values by value and reference values by reference.

This is just an elaborate way of saying that you're copying everything written on one sticky note to another (it doesn't matter whether you're copying a primitive value or a reference).

When copying references, the object being referenced doesn't move (e.g. my wife's grocery list will always stay under my keyboard, but I can take the sticky note I copied anywhere I want - the original sticky note will still be on the fridge).

Edit 2: In response to the comment posted by @LacViet:

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.

Consider the following C program:

#include <stdio.h>

int main() {
    int a = 10;
    int b = 20;
    int c = a + b;
    printf("%d", c);
    return 0;
}

When we compile this program we get an executable file. The executable file is divided into multiple segments (or sections). These segments include the stack segment, the code segment, the data segment, the extra segment, etc.

  1. The stack segment is used to store the state of the program when a function or interrupt handler is called. For example, when function f calls function g then the state of function f (all the values in the registers at that time) are saved in a stack. When g returns control to f then these values are restored.
  2. The code segment holds the actual code to be executed by the processor. It contains a bunch of instructions the processor must execute like add eax, ebx (where add is the opcode, and eax & ebx are arguments). This instruction adds the contents of registers eax and ebx and stores the result in the register eax.
  3. The data segment is used to reserve space for variables. For example, in the above program, we need to reserve space for the integers a, b and c. In addition, we also need to reserve space for the string constant "%d". Variables reserved thus have a fixed address in memory (after linking and loading).
  4. In addition to all of these, you're also give a little bit of extra space by the Operating System. This is called the heap. Any extra memory you need is allocated from this space. Memory allocated in this way is called dynamic memory.

Let's see a program with dynamic memory:

#include <stdio.h>
#include <malloc.h>

int main() {
    int * a = malloc(3 * sizeof(int));

    a[0] = 3;
    a[1] = 5;
    a[2] = 7;

    printf("a: %d\nb: %d\nc: %d\n", a[0], a[1], a[2]);

    return 0;
}

Because we want to allocate memory dynamically we need to use pointers. This is because we want to use the same variable to point to an arbitrary memory location (not necessarily the same memory location every time).

So we create an int pointer (int *) called a. The space for a is allocated from the data segment (i.e. it's not dynamic). Then we call malloc to allocate the contiguous space for 3 integers from the heap. The memory address of the first int is returned and stored in the pointer a.

Q: What did we learn?

A: A fixed amount of space is allocated for all variables. Each variable has a fixed address. We may also allocate extra memory from the heap and store the address of this extra memory in a pointer. This is called a dynamic memory scheme.

Conceptually this is similar to what I explained about variables being sticky notes. All variables (including pointers are sticky notes). However, pointers are special because they reference a memory location (which is like referencing an object in JavaScript).

However, this is where the similarities end. Here are the differences:

  1. In C everything is passed by value (including addresses in pointers). To pass a reference you need to use indirection via pointers. JavaScript only passes primitives by value. Passing references is handled transparently by the engine and is just like passing any other variable.
  2. In C you can create a pointer to a primitive data type like int. In JavaScript, you cannot create a reference to a primitive value like number. All primitives are always stored by value.
  3. In C you may perform various operations on pointers. This is called pointer arithmetic. JavaScript doesn't have pointers. It only has references. Thus you can't perform any pointer arithmetic.

Besides these three the biggest difference between C and JavaScript is that all variables in JavaScript actually pointers. Because JavaScript is a dynamic language the same variable may be used to store a number and a string at different points of time.

JavaScript is an interpreted language, and the interpreter is usually written in C++. Thus all variables in JavaScript are mapped to objects in the host language (even primitives).

When we declare a variable in JavaScript the interpreter creates a new generic variable for it. Then when we assign it a value (be it a primitive or a reference) the interpreter simply assigns a new object to it. Internally it knows which objects are primitive and which are actually objects.

Conceptually it's like doing something like this:

JSGenericObject ten = new JSNumber(10); // var ten = 10;

Q: What does this mean?

A: It means that all the values (primitives and objects) in JavaScript are allocated from the heap. Even the variables themselves are allocated from the heap. It's wrong to state that primitives are allocated from the stack and only objects are allocated from the heap. This is the biggest difference between C and JavaScript.

Aadit M Shah
  • 67,342
  • 26
  • 146
  • 271
  • 2
    Hi Aadit M Shah, your answer is very clear. Dispite its length, it really interesting and grasp my atention. I did read it from beginning to end. But..(sory to say that) that I need a explaination for heap and stack like you did above rather than thing you have invested time in to explain. I have rated you answer but..sory I cann't accept it. Could you please make a illustration about heap and stack, I will definately very appreciate. Thank you. – Lac Viet Nov 07 '12 at 12:03
  • 2
    aadit m shah, your analogy is super helpful and really helps to understand the material better! thanks for sharing. – wmock Mar 27 '13 at 04:40
  • 2
    Heh, love the analogy! Read it till the end and just wanted to add note 8 :). Just to make it clear that you're manipulating the same object: http://jsfiddle.net/DefML/ – smets.kevin Oct 14 '13 at 19:44
  • Using the analogy, for a very long string (primitive type), is it written on a sticky note, or on a long piece of paper, with the location of the paper written on the sticky note? – xesxz Jul 26 '15 at 07:57
  • 1
    Whoah, usually not a fan of protracted metaphors for programming stuff but this is a fantastic explanation – iono Feb 08 '17 at 07:35
  • Reference values are not passed by reference as edit 1 claims. Answer should be updated to reflect that all variables are passed by value in JavaScript, even object references. – May Oakes Jun 18 '17 at 16:45
  • @BrynnMahsman That's incorrect. Reference values are indeed passed by reference. Passing **by reference** by definition means that you're passing the reference of the object and not the object itself. Passing **by value** by definition means that you're *copying* the value and passing the copy. If you were to pass a reference value **by value** then you'd create a copy of the reference value (shallow or deep) and pass that copy. That's not what happens. Hence, my answer is correct. – Aadit M Shah Jun 18 '17 at 17:07
  • 1
    That is not what pass by reference means. Passing by reference is no way the same as passing a reference; you can pass a reference by value or by reference. See this answer for details https://stackoverflow.com/a/6605700 – May Oakes Jun 18 '17 at 21:32
  • Hey @AaditMShah. Can you tell me, am I allowed to use this analogy on the blog that I am writing? What are the terms of using this post/analogy? Thanks for the great post – Learn on hard way Feb 23 '19 at 13:26
  • 1
    @Learnonhardway Sure. You can use this analogy on your blog. Just give credit where credit is due (i.e., don't pass off the idea as your own and provide a link to my original answer). – Aadit M Shah Feb 25 '19 at 12:58
  • 1
    @MayOakes is right. Javascript arguments are passed by value. Consider this code: function setName(obj){obj.name ="Nick"; obj = new Object(); obj.name="Tom";} let person = new Object; setName(person); console.log(person.name); It will be printed "Nick", if the passing were by reference woud have returned "Tom" – Umbert Jan 21 '20 at 18:10
70

A variable can hold one of two value types: primitive values or reference values.

  • Primitive values are data that are stored on the stack.
  • Primitive value is stored directly in the location that the variable accesses.
  • Reference values are objects that are stored in the heap.
  • Reference value stored in the variable location is a pointer to a location in memory where the object is stored.
  • Primitive types include Undefined, Null, Boolean, Number, or String.

The Basics:

Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties.

Updated:

JavaScript has 6 primitive data types: String, Number, Boolean, Null, Undefined, Symbol (new in ES6). With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Sagar Kharche
  • 1,987
  • 2
  • 20
  • 31
Talha
  • 17,441
  • 7
  • 45
  • 63
  • 7
    Yes. But primitive types inlude: `string, number, boolean, null, undefined` - `String` with capital "S" is an object wrapper for `string`. See: [MDN Glossary - Primitive](https://developer.mozilla.org/en-US/docs/JavaScript/Glossary#primitive) – jfrej Nov 07 '12 at 09:33
  • 3
    The important difference is that when a reference value is passed to a function, and the function modifies its contents, that change is seen by the caller and any other functions that have references to the object. – Barmar Nov 07 '12 at 09:38
  • 1
    @Talha - Do you really need to explain low-level concepts like dynamic memory allocation when teaching a high-level language like JavaScript? – Aadit M Shah Nov 07 '12 at 10:24
  • Thank Talha your answer are really helpful – Lac Viet Nov 07 '12 at 10:30
  • @AaditMShah you r right, but a comment on this that's why answer is getting complex a little – Talha Nov 07 '12 at 11:10
  • @Talha - I'm not sure I understood what you said by `a comment on this that's why answer is getting complex a little`. Care to explain? – Aadit M Shah Nov 07 '12 at 11:53
  • What do you mean by "All primitives are immutable" ? It can be changed right ? – Santosh Dec 29 '16 at 04:45
  • 6
    Whether values are stored on the stack or heap is not determined by their type in JS. It depends on the lifetime of the variable it is stored in (affected by scopes and especially closures, and depending upon the analytical capabilities of the engine). – Bergi Jun 05 '17 at 23:42
4

In javascript the Primitive values are data that are stored on the stack.

Primitive value is stored directly in the location that the variable accesses.

And the Reference values are objects that are stored in the heap.

Reference value stored in the variable location is a pointer to a location in memory where the object is stored.

JavaScript supports five primitive data types: number, string, Boolean, undefined, and null.

These types are referred to as primitive types because they are the basic building blocks from which more complex types can be built.

Of the five, only number, string, and Boolean are real data types in the sense of actually storing data.

Undefined and null are types that arise under special circumstances. The primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

And the Reference types can be of any length -- they do not have a fixed size.

sohel khalifa
  • 5,528
  • 3
  • 32
  • 47
  • A boolean in JavaScript occupies 4 bytes: https://stackoverflow.com/questions/4905861/memory-usage-of-different-data-types-in-javascript – doubleOrt Feb 13 '18 at 15:13
1

A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit. The number type is the largest of the primitive types. If each JavaScript variable reserves eight bytes of memory, the variable can directly hold any primitive value.

This is an oversimplification and is not intended as a description of an actual JavaScript implementation.

Reference types are another matter, however. Objects, for example, can be of any length -- they do not have a fixed size. The same is true of arrays: an array can have any number of elements. Similarly, a function can contain any amount of JavaScript code. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value. Typically, this reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.

The distinction between primitive and reference types is an important one, as they behave differently. Consider the following code that uses numbers (a primitive type):

var a = 3.14;  // Declare and initialize a variable
var b = a;     // Copy the variable's value to a new variable
a = 4;         // Modify the value of the original variable
alert(b)       // Displays 3.14; the copy has not changed

There is nothing surprising about this code. Now consider what happens if we change the code slightly so that it uses arrays (a reference type) instead of numbers:

var a = [1,2,3];  // Initialize a variable to refer to an array
var b = a;        // Copy that reference into a new variable
a[0] = 99;        // Modify the array using the original reference
alert(b);         // Display the changed array [99,2,3] using the new reference

If this result does not seem surprising to you, you're already well familiar with the distinction between primitive and reference types. If it does seem surprising, take a closer look at the second line. Note that it is the reference to the array value, not the array itself, that is being assigned in this statement. After that second line of code, we still have only one array object; we just happen to have two references to it.

noddy
  • 11
  • 2
  • Thank your for the explanation, as well as the code snippets! To my understanding, the reason behind objects and arrays being reference types is that they could(!) become so huge in size, it would be inefficient to store them on the stack, right? – Matt Dec 28 '17 at 22:31
  • 1
    yes you are right! generally arrays are huge in size. so copying them multiple times while may take up whole space. – noddy Jan 13 '18 at 04:10
1

As already mentioned in the accepted answer and the highest voted answer, primitive values are data that are stored in stack and reference values are object that are stored in heap.

But what does this actually mean? How do they perform differently in your codes?

Primitive values are accessed by value. So when you assign an variable (var a) that has a primitive value to another variable (var b), the value of the variable (a) gets copied into the new variable (b). And when you change the value of the new variable (b), the value of the original variable remain unchanged.

When you assign a variable (var x) that has a reference value to another variable (var y), the value stored in the variable (x) is also copied into the new variable (y). The difference is that the values stored in both variables now are the reference of the actual object stored in the heap. This means that, both x and y are pointing to the same object. So when you change the value of the new variable (y), the value of the original valuable (x) is also changed (because the actual object in the heap is changed).

Jeremy Cai
  • 11
  • 1
0

A primitive value is a datum that is represented at its lowest level of the language implementation and in JavaScript is one of the following types: number, string, Boolean, undefined, and null.

0

Primitive versus reference:

Variable are segments of memory (RAM) which the javascript engine reserves to hold your data. Within these variables can be stored 2 kinds of values:

  • Actual data: For example a string or number. This means that the actual memory (i.e. the bytes in memory) hold the data itself.
  • References to objects: For example Array objects or Function objects. This means that this variable just holds a reference to another location in memory where this object resides.

Difference between primitive and reference value:

When a primitive value gets assigned to a variable the data (values of the bits) just copied. For example:

Primitive values:

let num1 = 10;

// What happens here is that the bits which are stored in the memory container 
// (i.e. variable num1) are literally copied into memory container num2
let num2 = num1;

Reference values:

let objRef1 = {prop1: 1}

// we are storing the reference of the object which is stored in objRef1
// into objRef2. Now they are pointing to the same object
let objRef2 = objRef1;

// We are manipulating the object prop1 property via the refernce which
// is stored in the variable objRef2
objRef2.prop1 = 2;

// The object which objRef1 was pointing to was mutated in the previous action
console.log(objRef1);
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113