Modifying a variable in a forEach loop

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Carey

    Modifying a variable in a forEach loop

    Hi

    I would have expected the following to change the value of a, but just
    discovered it doesn't.

    var forEach = function () {
    var a = "a";
    [a].forEach(functi on (v, i) {
    console.log("v= " + v);
    v = i;
    console.log("v= " + v);
    });
    console.log("a= " + a);
    };

    The output is:
    v=a
    v=0
    a=a

    I'm not really sure why, I'd be very grateful if someone could
    explain.
    Thanks

    Paul
  • slebetman

    #2
    Re: Modifying a variable in a forEach loop

    On Oct 7, 7:15 pm, Paul Carey <paul.p.ca...@g mail.comwrote:
    Hi
    >
    I would have expected the following to change the value of a, but just
    discovered it doesn't.
    >
    var forEach = function () {
    var a = "a";
    [a].forEach(functi on (v, i) {
    console.log("v= " + v);
    v = i;
    console.log("v= " + v);
    });
    console.log("a= " + a);
    >
    };
    >
    The output is:
    v=a
    v=0
    a=a
    >
    I'm not really sure why, I'd be very grateful if someone could
    explain.
    In javascript, plain numbers and strings are passed by value. Only
    objects are passed by reference. If we modify your code slightly
    you'll see the expected behavior:

    var forEach = function () {
    var a = {value:"a"};
    [a].forEach(functi on (v, i) {
    console.log("v" ,v);
    v.value = i;
    console.log("v" ,v);
    });
    console.log("a" ,a);
    };

    output:
    v Object value=a
    v Object value=0
    a Object value=0

    Comment

    • dhtml

      #3
      Re: Modifying a variable in a forEach loop

      slebetman wrote:
      On Oct 7, 7:15 pm, Paul Carey <paul.p.ca...@g mail.comwrote:
      >
      In javascript, plain numbers and strings are passed by value. Only
      objects are passed by reference. If we modify your code slightly
      you'll see the expected behavior:
      >
      Actually, object references are passed by value.

      Garrett

      Comment

      Working...