Categories
interview

Passing an object vs primitive data type in Js

In Javascript, when you pass a primitive data type like String or Int in Java to a function or a method, and a function modifies it, then this does not effect the actual data being passed. For example,

var a = 0;

var increment = function(b) {
  b = 1;
}

increment(a);
console.log(a);

Output

0

Demo

But if you pass an object, array for example any changes made will reflect on the actual object (data) being passed to the method or function.

var a = [0, 1, 2];

var increment = function(b) {
  b[2] = 0;
}

increment(a);
console.log(a);

Output

[0, 1, 0]

Demo

var obj = {
  greeting: 'Hello'
};

var modify = function(b) {
  b['greeting'] = 'World';
}

modify(obj);
console.log(obj);

Output

{greeting: 'World'}

Demo

The reason we see this in Javascript is that when we pass an array (special kind of object) or an object, then their reference is passed into the function. Hence any modifications made on them will reflect on the original object or array.