Sunday 9 December 2018

JavaScript: Explain pass-by-value and pass-by-reference with example

If you pass primitive parameter to a function, then the parameters are passed to the function by value.

HelloWorld.js
function square(number){
  number = number * number;
  return number;
}

var n = 100;

console.log(`Value of n before calling square function is ${n}`);
console.log(`Square of ${n} is ${square(n)}`);
console.log(`Value of n after calling square function is ${n}`);

Output
Value of n before calling square function is 100
Square of 100 is 10000
Value of n after calling square function is 100

If you pass an object to the function as an argument, then the argument is passed by reference. If the function changes the properties of the object, then the changes will be visible outside.

HelloWorld.js
function change_me(emp){
  emp.firstName = 'Ram';
  emp.age = 55;
}

var employee = {
    firstName: "Krishna",
    lastName: "Gurram",
    age: 29,

    toString: function() {
        return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", age = " + this.age + "]";
    }
}

console.log(`employee before calling change_me ${employee}`);
change_me(employee);
console.log(`employee after calling change_me ${employee}`);


Output
employee before calling change_me [firstName = Krishna, lastName = Gurram, age = 29]
employee after calling change_me [firstName = Ram, lastName = Gurram, age = 55]



Previous                                                 Next                                                 Home

No comments:

Post a Comment