Tuesday, May 2, 2017

JavaScript pass by reference and pass by value




Pass by value

When we change the value in the inner scope a copy of the value is created, This is known as pass by value.



/*Here we changed the value of the inner scope, 
  When we change the value in the inner scope a copy 
of the value is created, This is known as pass by value
*/
"use strict"
var a=10;
function passbyValue(a)
{
    a=20;
    console.log(a);
}
passbyValue()
console.log(a);

Output

Pass by reference

When we change the value of the property of an object the property value changes at the reference
/**
 * We can pass by reference an object and can only change the property values
 * It cannot add or change the property
 */
var employee={
    firstName:'Prathap',
    lastName:'Kudupu'

}
function passbyReference(employee)
{
    employee.firstName="Atharv";
    console.log(employee);
}
passbyReference(employee);
console.log(employee);



Pass by reference (Modify properties)

We can only modify the values of the property. We cannot edit the property name.
/**
 * When we modify the property of an object with reference, then the changes 
would not be affected.
 */
var employee={
    firstName:'Prathap',
    lastName:'Kudupu'

}
function passbyReference(employee)
{
    employee={a:"change"};
    console.log(employee);
}
passbyReference(employee);
console.log(employee);

Output

No comments:

Post a Comment