Anil Namde Anil Namde - 2 years ago 86
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.

Answer Source

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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download