Home « Previous Next »

Pass by value and Pass by reference

In JavaScript all the primitive types are passed by value (strings, numbers and booleans) and objects are passed by reference.

Pass by value

If we change the value of the primitive type which is passed into a function, then any changes to this variable within the function, will not affect the variable in the outerscope.

In this case only a copy of the variable is passed into the function.

Example:

var dog = 'Retriever';

function changeDog(dog) {
  dog = 'Pug';
}

changeDog(dog);
console.log(dog);  // Retriever

Pass by reference

Non primitive types like Objects are passed as reference.

Example 1:

var dog = {};

function changeDog(dog) {
  dog.name = 'Pug'
}

changeDog(dog);
console.log(dog);  // { name: 'Pug'}

Does this mean that, we can change what dog is pointing to? Lets see that with the example below

Example 2:

var dog = { name: 'Retriever' };

function changeDog(dog) {
  dog =  { name: 'Pug' };
}

changeDog(dog);
console.log(dog);  // { name: 'Retriever'}
Home « Previous Next »