16

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.

Anil Namde
  • 6,452
  • 11
  • 63
  • 100
  • possible duplicate of [Is JavaScript is a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-is-a-pass-by-reference-or-pass-by-value-language) – Matthew Jones May 14 '10 at 14:54

5 Answers5

31

Other answers to this question are correct - all variables are passed by value in JavaScript, and sometimes that value points to an object.

When a programming language supports passing by reference, it's possible to change where the variable points from inside a function. This is never possible in JavaScript.

For example, consider this code which attempts to reassign the passed variable to a new value:

function changeCaller( x ) {
    x = "bar";  // Ha ha!
}

function testChangeCaller() {

    var x = "foo";

    changeCaller(x);

    alert(x); // still "foo"

}

testChangeCaller();

Attempts to point variables at new objects fails in the same way the above example fails to reassign a primitive string:

function changeCaller( x ) {
    x = new Object(); // no longer pointing to the same object
    x.a = "bar";
}

function testChangeCaller() {

    var x = new Object();
    x.a = "foo";

    changeCaller(x);

    alert(x.a); // still "foo"

}

testChangeCaller();

The feature which leads people to believe they're dealing with a pass-by-reference scenario is when modifying objects. You can make changes to an object or array, because the local variable points to the same object:

function changeCaller( x ) {
    x.a = "bar";
}

function testChangeCaller() {

    var x = new Object();
    x.a = "foo";

    changeCaller(x);

    alert(x.a); // now "bar", since changeCaller worked on the same object

}

testChangeCaller();

Hope this helps!

jimbo
  • 11,004
  • 6
  • 29
  • 46
14

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"

JavaScript

foo = {"foo": true};
bar = foo;     // assign value by reference
bar = {"bar": true};
alert(JSON.stringify(foo)); // -> output: '{"foo": true}
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 66
    For all intents and purposes, objects (including arrays) are passed by reference. Saying that "you are passing by value, but the value is a reference to the object" is another way of saying "you are passing by reference". Unless you are just trying to confuse people. – rob May 14 '10 at 15:21
  • 7
    @rob, not for **all** intents and purposes. For example, many WMI scripting calls require that you pass a variable to the function by reference, so that the return value of that function can be an error number. Instead of returning the result, it assigns the result to the variable passed in. VBScript can handle this just fine but JScript/JavaScript cannot because it cannot pass a reference to the variable in. They are not the same thing and I'm not trying to confuse people, I'm trying unconfuse people by expelling a myth that's already caused a lot of confusion. – Andy E May 14 '10 at 15:26
  • 9
    No, @rob, that's not the case. The *value* that is passed is the value of the reference. In a true pass-by-reference language, the compiler introduces a pointer that's invisible in the code. In a pass-by-reference language you can write the notorious "swap two ints" function naturally. The value of a variable in Javascript is *always* a reference to an object, and when you call a function you're *always* passing that value. If Number had methods on it that allowed the value to be changed, it would be more clear, perhaps. – Pointy May 14 '10 at 15:31
  • @Andy E's head, the example you give works fine in Javascript if it is an object, but not if it is a primitive, just as I said. Example: for a function that multiplies a number (int or float), and you've got to return the result as a value rather than modifying the number and using the error message for whatever. Now try doing the same, modifying a point object, which has an x and a y: function multiplyPoint (point, factor) { if (isNan(factor) return -1; point.x *= factor; point.y *= factor; return 0; } – rob May 14 '10 at 19:56
  • 3
    @rob: Of course it will work, you misunderstood the answer and the comments. The value of the point variable is a reference to the object, but point itself is not a reference to the variable that was passed in. Pass by reference is different in the way that if you set `point = "a string and not an object";` inside the function, the original variable that was passed to the function would be modified. In JavaScript this is not the case. Pass by reference and pass value by reference are not the same thing. – Andy E May 14 '10 at 20:19
  • 1
    Obviously we won't agree on this, I understand what you are saying but don't think it serves most people to view it that way. Crockford considers Javascript a "pass by reference language" (http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-5), and javascript's handling of objects is pretty much identical to C++ when passing by reference, and it's handling of primitives is pretty much identical to C++'s when passing by value. I'm sure we could debate it forever, but this will be my final word. :) – rob May 14 '10 at 23:26
  • 1
    @rob: we'll agree to disagree then ;-) I honestly think it's confusing to call it a pass by reference language, when you work with some other languages that pass by reference and particularly in this case extra clarity is needed to understand the difference. Final word ;-) – Andy E May 14 '10 at 23:39
  • P.S. C++ supports true pass by reference, in a similar manner to PHP's `&`. – Andy E May 15 '10 at 00:12
  • Can you explain this behavior? `var a = {foo:true}; var b = a; b.foo = false; alert(a.foo);` alerts false. – 000 Apr 25 '12 at 13:43
  • 2
    @joeframbach: yes. `b` is assigned with a reference to the same object that `a` also refers to. That is, both variables hold a reference to the same object, but `b` is not a reference to `a`. With true pass by reference, `b = false` would also change the value of `a`. Compare the PHP example (assign/pass by reference) to the JavaScript example (assign/pass reference by value). – Andy E Apr 25 '12 at 13:57
  • 1
    I agree with the other comments - this is a HORRIBLE example. It's not at ALL the same as the php example. – jscul Apr 17 '18 at 03:52
  • It depends on 'pass-by-reference' definition. Probably the most common is 'When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.' According to this definition Javascript is NOT pass-by-reference, regardless of whether you pass object or not. – Alex Che Feb 05 '21 at 11:55
2

Regard the discussion, the considerations about "value" and "reference" are wrong on the exception of the Pointy comment. Javascript like other reference laguages like c# or java, don't pass a referece to the variable itself to the method, but the reference of the object referenced by the variable. What the people here is expecting, is passing a pointer to the variable which is referencing the object, pass by pointer is not the same as pass by reference, and sure is not the same as pass by value.

The behavior expected here is pass by pointer. Pass by reference sends the reference to the object. Pass by value copy the object stored in the variable and pass the copy to the method.

0

The pass by value, pass by reference discussion is an evil meme. This evil meme crops up in Java discussions too.

It's simple: The bit pattern of the value is copied to the parameter. It doesn't matter if the bit pattern is an int or if it's the address of an object -- it's just copied, bit by bit, into the parameter. It couldn't be simpler. The run-time isn't doing something special for primitives versus references. It simply, and always, just makes a copy of the value.

The computer science term for this is "pass by value."

Pass by reference just isn't used in programming any more. In older languages, like Pascal, you could code a function to directly alter the value in the calling routine. So, for example, an int variable in the calling routine could be altered in the called function.

0

Primitive values are passed via value and objects are passed via reference.

Strings are immutable, so they are passed via reference although they are considered as primitive type.

dev1223
  • 1,148
  • 13
  • 28