Primitive value vs Reference value - javascript

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?

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:
Yes or no (a boolean).
My age (a number).
My name (a string).
Nothing at all (undefined).
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?
A list of groceries is obviously not simple (erm... primitive) data.
My wife wrote it on a longer piece of paper.
She wrote where to find it in a sticky note.
Honey, the list of groceries is under your keyboard.
To recap:
The actual object (the list of groceries) is under my keyboard.
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.
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.
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.
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).
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:
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.
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.
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.

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.

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.

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.

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).

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.

Related

In what way are datatypes immutable? [duplicate]

If a string is immutable, does that mean that....
(let's assume JavaScript)
var str = 'foo';
alert(str.substr(1)); // oo
alert(str); // foo
Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?
If the string was mutable, does that mean the 2nd alert() would return oo as well?
It means that once you instantiate the object, you can't change its properties. In your first alert you aren't changing foo. You're creating a new string. This is why in your second alert it will show "foo" instead of oo.
Does it mean, when calling methods on
a string, it will return the modified
string, but it won't change the
initial string?
Yes. Nothing can change the string once it is created. Now this doesn't mean that you can't assign a new string object to the str variable. You just can't change the current object that str references.
If the string was mutable, does that
mean the 2nd alert() would return oo
as well?
Technically, no, because the substring method returns a new string. Making an object mutable, wouldn't change the method. Making it mutable means that technically, you could make it so that substring would change the original string instead of creating a new one.
On a lower level, immutability means that the memory the string is stored in will not be modified. Once you create a string "foo", some memory is allocated to store the value "foo". This memory will not be altered. If you modify the string with, say, substr(1), a new string is created and a different part of memory is allocated which will store "oo". Now you have two strings in memory, "foo" and "oo". Even if you're not going to use "foo" anymore, it'll stick around until it's garbage collected.
One reason why string operations are comparatively expensive.
Immutable means that which cannot be changed or modified.
So when you assign a value to a string, this value is created from scratch as opposed to being replaced. So everytime a new value is assigned to the same string, a copy is created. So in reality, you are never changing the original value.
I'm not certain about JavaScript, but in Java, strings take an additional step to immutability, with the "String Constant Pool". Strings can be constructed with string literals ("foo") or with a String class constructor. Strings constructed with string literals are a part of the String Constant Pool, and the same string literal will always be the same memory address from the pool.
Example:
String lit1 = "foo";
String lit2 = "foo";
String cons = new String("foo");
System.out.println(lit1 == lit2); // true
System.out.println(lit1 == cons); // false
System.out.println(lit1.equals(cons)); // true
In the above, both lit1 and lit2 are constructed using the same string literal, so they're pointing at the same memory address; lit1 == lit2 results in true, because they are exactly the same object.
However, cons is constructed using the class constructor. Although the parameter is the same string constant, the constructor allocates new memory for cons, meaning cons is not the same object as lit1 and lit2, despite containing the same data.
Of course, since the three strings all contain the same character data, using the equals method will return true.
(Both types of string construction are immutable, of course)
The text-book definition of mutability is liable or subject to change or alteration.
In programming, we use the word to mean objects whose state is allowed to change over time. An immutable value is the exact opposite – after it has been created, it can never change.
If this seems strange, allow me to remind you that many of the values we use all the time are in fact immutable.
var statement = "I am an immutable value";
var otherStr = statement.slice(8, 17);
I think no one will be surprised to learn that the second line in no way changes the string in statement.
In fact, no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable – they cannot change, we can only ever make new strings.
Strings are not the only immutable values built into JavaScript. Numbers are immutable too. Can you even imagine an environment where evaluating the expression 2 + 3 changes the meaning of the number 2? It sounds absurd, yet we do this with our objects and arrays all the time.
Immutable means the value can not be changed. Once created a string object can not be modified as its immutable. If you request a substring of a string a new String with the requested part is created.
Using StringBuffer while manipulating Strings instead makes the operation more efficient as StringBuffer stores the string in a character array with variables to hold the capacity of the character array and the length of the array(String in a char array form)
From strings to stacks... a simple to understand example taken from Eric Lippert's blog:
Path Finding Using A* in C# 3.0, Part Two...
A mutable stack like System.Collections.Generic.Stack
is clearly not suitable. We want to be
able to take an existing path and
create new paths from it for all of
the neighbours of its last element,
but pushing a new node onto the
standard stack modifies the stack.
We’d have to make copies of the stack
before pushing it, which is silly
because then we’d be duplicating all
of its contents unnecessarily.
Immutable stacks do not have this problem. Pushing onto an immutable
stack merely creates a brand-new stack
which links to the old one as its
tail. Since the stack is immutable,
there is no danger of some other code
coming along and messing with the tail
contents. You can keep on using the
old stack to your heart’s content.
To go deep on understaning immutability, read Eric's posts starting with this one:
Immutability in C# Part One: Kinds of Immutability
One way to get a grasp of this concept is to look at how javascript treats all objects, which is by reference. Meaning that all objects are mutable after being instantiated, this means that you can add an object with new methods and properties. This matters because if you want an object to be immutable the object can not change after being instantiated.
Try This :
let string = "name";
string[0] = "N";
console.log(string); // name not Name
string = "Name";
console.log(string); // Name
So what that means is that string is immutable but not constant, in simple words re-assignment can take place but can not mutate some part.
The text-book definition of mutability is liable or subject to change or alteration. In programming, we use the word to mean objects whose state is allowed to change over time. An immutable value is the exact opposite – after it has been created, it can never change.
If this seems strange, allow me to remind you that many of the values we use all the time are in fact immutable.
var statement = "I am an immutable value"; var otherStr = statement.slice(8, 17);
I think no one will be surprised to learn that the second line in no way changes the string in statement. In fact, no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable – they cannot change, we can only ever make new strings.
Strings are not the only immutable values built into JavaScript. Numbers are immutable too. Can you even imagine an environment where evaluating the expression 2 + 3 changes the meaning of the number 2? It sounds absurd, yet we do this with our objects and arrays all the time.

Is Javascript not a dynamic programming language, why is the DOM not modified? [duplicate]

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?
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:
Yes or no (a boolean).
My age (a number).
My name (a string).
Nothing at all (undefined).
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?
A list of groceries is obviously not simple (erm... primitive) data.
My wife wrote it on a longer piece of paper.
She wrote where to find it in a sticky note.
Honey, the list of groceries is under your keyboard.
To recap:
The actual object (the list of groceries) is under my keyboard.
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.
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.
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.
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).
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:
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.
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.
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.
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.
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.
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.
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).
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.

What is meant when we say that primitive values are immutable? [duplicate]

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?
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:
Yes or no (a boolean).
My age (a number).
My name (a string).
Nothing at all (undefined).
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?
A list of groceries is obviously not simple (erm... primitive) data.
My wife wrote it on a longer piece of paper.
She wrote where to find it in a sticky note.
Honey, the list of groceries is under your keyboard.
To recap:
The actual object (the list of groceries) is under my keyboard.
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.
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.
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.
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).
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:
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.
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.
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.
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.
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.
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.
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).
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.

Javascript array to linked list, and understanding memory

I have the following code to convert an array to a linked list:
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
This code was given to me so I'm trying to understand it. I get the basic intuition/gist of it (I've worked with linked lists, took a data structures class in Java already, understand basics of pointers in C), etc.
However, something's not clicking and I want to make sure I can see what's going on. So let's consider we create a variable, list, referring to memory space whose value is declared to be null. Let's say this "memory address" of this is 0001:
0001: [null] list
So what happens after the first iteration of our loop? This is my interpretation. list now refers to a new chunk of space. That is, by re-defining list in the line:
list = {value: array[i], rest: list};
we created a "new" object that occupies new space. So now we might have:
0001: [null]
0002: [array[i]] list.value
0003: [null] list.rest
(I'm not quite sure where exactly list is "pointing" to now, assuming 0002, though conceptually I guess that's kind of moot in Javascript)
Is this understanding correct? I'm used to thinking of data structures a la Java, where an object like list has already-defined blocks of space every time an instance is created. I've worked with Python but have not built linked lists with it before. From this I assume a language like Javascript is fluid in that you can just have a variable be null, then have it refer to a hash, then when you set it to be another hash it creates a "new" hash, etc.
Thanks!
First off, there is no native data structure in JavaScript which is a linked list, we have Objects and we have Arrays (which confusingly are special cases of Objects).
The code you've shown us here makes Objects by using object literals.
This seems to be more a question about using the same identifier on both sides of an =
The variable on the RHS of an = will point to the thing before it changes on the LHS
// say we have
var foo = {};
// Then
foo = {"fizz": foo};
is equivalent to having
var foo = {};
var t = foo;
foo = {"fizz": t}; // `foo` becomes a new object in a different memory location
// that points to `t`s target, meaning that `t` is referencable through `foo` and so
// won't be GC'd if the identifier `t` is cleaned up from namespace
You might find this be counter-intuitive based on the usual left-to-right order of execution, but if you think about it - you can't "set" until you know what to set, so until the RHS has finished you can't update the identifier from the LHS
So if you loop this, you might end up with a structure like
foo; // Object # e.g. 0x30
foo.fizz; // Object # e.g. 0x20
foo.fizz.fizz; // Object # e.g. 0x10
foo.fizz.fizz.fizz; // undefined
Where each Object has it's own hash map which points back to the previous one (when looking up fizz) until you run out of Objects, and none of the memory gets GCd because each one is still reachable. How an environment actually implements this isn't specified in the spec, so it isn't a requirement that the memory location of an Object never moves, but it's location in memory is not something you are able to see or interact with (it's all done behind the scenes). Therefore, for all in-environment purposes, you can think of the memory locations as static.

How is the variable sized JavaScript string a primitive type?

From what I understand, the (basic) string type in JavaScript is a primitive type, meaning its variables are allocated on the stack.
I would have thought that for a type to be allocatable on the stack, it needed to have a fixed size -- something which presumably holds true for the other primitive types like boolean, number, etc.
Am I somehow wrong to assume that, or is some other internal magic used to make strings in JavaScript primitive types?
EDIT:
This gets more complicated when one considers that JavaScript is loosely typed. Which makes me wonder how any local variable can be allocated on the stack.... given that the size of what might be assigned to it during the course of a function is not fixed.
But I guess (a perhaps simplified) answer to this might be that all local variables could be assigned a fixed maximum size on the stack. Say this is 8 bytes which I think is the size of the number type, and should be large enough to accommodate all the other primitive types (except the string) as well as memory addresses (for when a local variable is assigned a reference type). But, surely strings cannot be limited to 8 bytes (or any size for that matter). Which makes me conclude that strings (even the primitive type ones) are not (cannot be) assigned on the stack. And hence the term "Primitive type" in JavaScript is used to mean a "basic/building block" type, rather than one which is necessarily allocated on the stack (contradicting what I have read in numerous sources including the book "Professional JavaScript..." by Nicholas Zakas).
Anyone have any other take or a pointer to a good source talking about this?
A string is a both an object and a primitive.
When doing:
var s = "this is a string";
you actually do:
var s = new string("this is a string");
behind the curtains.
The first being a primitive array with characters, on which the second one refers.
Strings are immutable, meaning they can't be changed. If you try to change it (i.e. reverse it), you will create a new string primitive, on which the object reference will point to.
The storage used to represent variables in the Javascript interpreter need not look anything like a stack - it's implementation dependent.
Strings aren't allocated on the stack
where a variable is allocated doesn't distinguish primitives from objects
Strings aren't primitives, they are of the class "string"
The difference between a primitive and a type is that types have methods and you can assign new properties to them:
var a = 1, b = {}, s = '';
a.foo = 1; // doesn't work, but no error either
b.foo = 1; // works
s.foo = 1; // doesn't work, but no error either
console.log(a.foo);
console.log(b.foo);
console.log(s.foo);
​
gives
undefined
1
undefined
So all in all, I'm not sure that using "primitive" makes sense in JavaScript since the line is blurred.
A string is a "value object" which means you can't change any of the properties. For example, when you replace characters in a string, you get a new string; the old string doesn't change.

Categories

Resources