What is the difference between 'Pass by Value' and 'Pass by Reference'?
In JavaScript, understanding the difference between "Pass by Value" and "Pass by Reference" is crucial for understanding how variable assignment and function calls work.
Pass by Value
let a = 10;
function modifyValue(x) {
x = 20;
console.log('Inside function: ', x); // 20
}
modifyValue(a);
console.log('Outside function: ', a); // 10
In this example, a is a number (a primitive value). When modifyValue(a) is called, the value 10 is copied to x. Inside the function, x is modified to 20, but this does not affect the original variable a.
Pass by Reference
let obj = { property: 10 };
function modifyObject(o) {
o.property = 20;
console.log('Inside function: ', o.property); // 20
}
modifyObject(obj);
console.log('Outside function: ', obj.property); // 20
In this example, obj is an object (a non-primitive value). When modifyObject(obj) is called, a reference to the object obj is passed to o. Inside the function, o.property is modified to 20, and this change is reflected in the original object obj.