Anil Namde Anil Namde - 4 months ago 6x
Javascript Question

Is there thing like pass by value pass by reference in JavaScript?

When i started learning function in C++ its all around pass by value and reference.
Is there something similar we have in javascript ?

If yes/not how it works in case of javascript?

Thanks all.


JavaScript is always pass by value, never pass by reference. A lot of people confuse this because of the way objects work.

There is no "pass by reference" for any variable in JavaScript (no, not even if an object is assigned to that variable). All variables and arguments are assigned by value. If the assigned value is an object, then the value of the new variable is a reference to that object, but assigning a new value/object to the new variable will not affect the original variable.

Some people term this behaviour passing "value by reference".

A comparison - PHP

$foo = "foo";
$bar = &$foo;  // assign by reference
$bar = "bar";
echo $foo; // -> output: "bar"


foo = {"foo": true};
bar = foo;     // assign value by reference
bar = {"bar": true};
alert(JSON.stringify(foo)); // -> output: '{"foo": true}