Primitive vs Reference types in javascript

In Javascript data types can be classified based on how they are passed:

  • value

    • Boolean
    • null
    • undefined
    • String
    • Number
  • reference

    • Array
    • Function
    • Object
  • data types which are passed by value are called primitive types

  • data types which are passed by revference, we refer to them collectively as Objects

Primitive

If a primitive type is assigned to a variable, we can think of that variable as containing the primitive value.

var x = 10;
var y = 'abc';
var z = null;

x contains 10, y contains 'abc'.

when we reassign values to these variable. the new values are simply copied into that variable.

var x = 10;
var y = 20;

var a = x;
var b = y;

Now you might think that since x is assinged to a, a must be same as x, and since y is assigned to b, b must be same as y; but its not.

you can check it like this

a === x;
// false
b === y;
// false

a and x are not the same variable, but both have the same value.

so changing one variable's value dosent effect other's value

function reassignMe(testVar){

    testVar = 20;

}

var primitiveVar = 10;

console.log(primitiveVar);
// 10;

reassignMe(primitiveVar);

console.log(primitiveVar);
// 10;

when we call reassignMe with argument primitiveVar. we are actually passing the value and not the variable reference itself, therefore when we reassign that inside the function the original variable is not effected.

Reference

Now lets taklk about the Object or Reference types.

var sampleArray = [10,20,30];

when we declare a reference type such as array, object, function, object of that type is getting created inside the memeory ( the heap ) and its memory location is returned which we store in a variable

so, in the above example sampleArray stores the address of the array which we created using the literal array syntax [ ]


function changeThatArray(arr) {
    arr[0] = 100;
}


var sampleArray = [10,20,30]

console.log(sampleArray[0]);
// 10

changeThatArray(sampleArray);

console.log(sampleArray[0]);
// 100

here we can see that the array is actually modified by the function. This is because array is a reference type, and is passed by reference.

so, when we pass an array as an argument the address of that array is passed as argument to the function.

One more thing

objects are mutable, meaning they can change ( unless we freeze it, however primitive types are immutable,

var name = "rohit";
name = "harshit";

So, when we are dealing with primitive types we don't actually mutate the value we replace the value with a new value.