What is the difference between 'Pass by Value' and 'Pass by Reference'?

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

  • Definition: When a variable is passed by value, a copy of the variable's value is made and passed to the function. This means that changes made to the parameter inside the function do not affect the original variable.
  • Applies to: Primitive data types in JavaScript (e.g., Number, String, Boolean, undefined, null, Symbol, BigInt).

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

  • Definition: When a variable is passed by reference, a reference to the actual variable is passed to the function. This means that changes made to the parameter inside the function affect the original variable.
  • Applies to: Non-primitive data types in JavaScript (e.g., Object, Array, Function).

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.


要查看或添加评论,请登录

Rauf Rzayev的更多文章

社区洞察

其他会员也浏览了