Day-6 - Is javascript pass by value or pass by reference?

sanjaybabu

C K Sanjay Babu

Posted on May 6, 2022

Day-6 - Is javascript pass by value or pass by reference?

It's both! Let's find out how.

Pass by value

Whenever a function is called, if the value of the variable is passed directly as the parameter, then the changes made to that parameter are not propagated beyond the function.

All primitive data types in javascript are passed by value.

Example

var a=10;
console.log("Value of 'a' before method called: "+a);
add(a);
function add(a){
   a++;
   console.log("Value of 'a' inside the method call: "+a);
}

console.log("Value of 'a' outside the method called: "+a);

/*
Output:
Value of 'a' before method called: 10
Value of 'a' inside the method call: 11
Value of 'a' outside the method called: 10
 */

Enter fullscreen mode Exit fullscreen mode

Pass by Reference

Whenever a function is called, if the address of the variable is passed as a parameter directly instead of making a copy of it and just sending the value alone, then it's pass by reference. As we are still referencing the address inside the function, any change made to the variable inside the function will be propagated throughout the program.

Objects and Arrays are passed by reference in javascript

Example

var user={
   id:1,
   firstName:"John",
   lastName:"Doe"
}

console.log("Value of 'user' before method called: "+user.firstName+" "+user.lastName);

print(user);

function print(user){
   user.lastName="Wick";
   console.log("Value of 'user' inside the method call: "+user.firstName+" "+user.lastName);
}

console.log("Value of 'user' outside the method call: "+user.firstName+" "+user.lastName);

/*
Output:
Value of 'user' before method called: John Doe
Value of 'user' inside the method call: John Wick
Value of 'user' outside the method call: John Wick
*/

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sanjaybabu
C K Sanjay Babu

Posted on May 6, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related