Modifying a variable in a forEach loop

Discussion in 'Javascript' started by Paul Carey, Oct 7, 2008.

  1. Paul Carey

    Paul Carey Guest

    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(function (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
     
    Paul Carey, Oct 7, 2008
    #1
    1. Advertisements

  2. Paul Carey

    Henry Guest

    Aren't you the person in the best position to explain why you expected
    the value of - a - to be changed? Given that a function's parameters
    (- v - in this case) have the same status as a function's local
    variables (in terms of scoping/visibility) there was never any reason
    for expecting assigning to a parameter to have any effect outside of
    the function where it happens. And given that Arrays are just
    sequences of values there is no reason for expecting a method
    operating upon an Array to have any effect on the value of a variable
    that was previously read in order to initialise one of its values.
     
    Henry, Oct 7, 2008
    #2
    1. Advertisements

  3. Paul Carey

    Paul Carey Guest

    Aren't you the person in the best position to explain why you expected
    Indeed. My mistake in oversimplifying an example.
     
    Paul Carey, Oct 7, 2008
    #3
  4. Paul Carey

    slebetman Guest

    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(function (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
     
    slebetman, Oct 8, 2008
    #4
  5. Paul Carey

    dhtml Guest

    Actually, object references are passed by value.

    Garrett
     
    dhtml, Oct 8, 2008
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.