Home  >  Q&A  >  body text

Are parameters passed in JavaScript by value or by reference?

<p>Primitive types (numbers, strings, etc.) are passed by value, but objects are unknown since they can both be passed by value (in which case we think the variable holding the object is actually the object reference), can also be passed by reference (in which case we consider the variable to hold the object itself). </p> <p>While it ultimately doesn't matter, I'd like to know how to render the parameter passing convention correctly. Is there an excerpt from the JavaScript specification that defines what the semantics about this should be? </p>
P粉394812277P粉394812277400 days ago518

reply all(1)I'll reply

  • P粉426906369

    P粉4269063692023-08-22 13:30:26

    It’s fun in JavaScript. Consider the following example:

    function changeStuff(a, b, c)
    {
      a = a * 10;
      b.item = "changed";
      c = {item: "changed"};
    }
    
    var num = 10;
    var obj1 = {item: "unchanged"};
    var obj2 = {item: "unchanged"};
    
    changeStuff(num, obj1, obj2);
    
    console.log(num);
    console.log(obj1.item);
    console.log(obj2.item);

    This will produce the following output:

    10
    changed
    unchanged
    
    • If obj1 is not a reference at all, then changing obj1.item has no effect on obj1 outside the function.
    • If the argument is a correct reference, then everything changes. num will be 100, obj2.item will be "changed". Instead, num remains 10, and obj2.item remains "unchanged".

    Actually, what happens is that the items passed are passed by value. But the item passed by value itself is a reference. Technically, this is called a shared call.

    In practical terms, this means that if you change the parameter itself (such as num and obj2), that will not affect the items passed in the parameter. However, if you change the internals of the parameter, that will be propagated back (like obj1).

    reply
    0
  • Cancelreply