About JavaScript argument passing

-23 Oct 2014-

Recently while writing some funky JavaScript code, I noticed an interesting behavior in relation to function arguments. Passing in variables containing primitive values as arguments will not allow the function to change the value of the variable. However, a function that takes in an object as argument has the ability to alter its contents.

Take the following code for example…

var primitiveVariable = 1,
    objectVariable = {value:1};
function mutate(someVariable){
  someVariable.value ? someVariable.value +=1 : someVariable +=1;


//  logs 1, the original value
// logs 2, which has been changed

This behaves this way because JavaScript does not pass arguments as reference or value every time. It follows a convention called call by sharing. This basically means that the whole value of a variable passed in cannot be changed, but the properties of a variable passed in can be changed. It’s a bit confusing, but it basically boils down to two points.

Go back