2

The following JS code behaves oddly:

var c = 0;
var a = 0;
myTest(8, 5);

function myTest(a,b) {
    console.log(a);
    a++;
    c++;
    console.log(a);
    return a;
}

console.log(a);
console.log(c);

https://jsfiddle.net/hwns1v4L/

If I take the "a" parameter out of the function, "a" increments by 1 and the third console log returns "a" as 1. Totally normal. But if I keep the "a" as a parameter in myTest function (as in the code above), it gets a value of 8, increments by 1 to 9, and the third console log returns a zero.

What is the explanation for this weird behavior? I am sorry if this is explained in another thread; I am too new for JS to produce really good google queries or understand advanced answers.

Bar Akiva
  • 1,089
  • 1
  • 11
  • 23
  • JavaScript is pass by value, like most other languages. This "weird" behavior is very common. https://en.m.wikipedia.org/wiki/Evaluation_strategy – Felix Kling Mar 21 '16 at 13:26

2 Answers2

3

What is the explanation for this weird behavior?

Because in Javascript variables are function scoped.

You never passed a and b to myTest method. You passed 8 and 5, so a and b which were part of myTest signature got new scope. a became 8 and b became 5 inside myTest.

Values of a and b inside myTest will not be used outside since their scope is limited to myTest.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I do however return `a`. If in the scope of the function `a` is 8 or 9, then how come when it's returned it is still 0? – Bar Akiva Mar 21 '16 at 13:05
  • @BarAkiva You returned a value, not variable. You didnt do `a = myTest(8,5)`, so a will not have new value. – gurvinder372 Mar 21 '16 at 13:07
1

Inside your function, you have a local a parameter. So any changes you make to that value, they will not reflect your globally defined a. Since you did not create a c variable or parameter inside the function, you will be changing the global c value.

var c = 0;             // Global c
var a = 0;             // Global a
var b = myTest(8, 5);  // Store the value of the local a from the function return.

function myTest(a,b) {
    console.log(a);    // This a is a local reference (8)
    a++;               // Increment local a
    c++;               // Increment global c
    console.log(a);    // Print local a               (9)
    return a;          // Return local a
}

console.log(a);        // Print global a              (0)
console.log(c);        // Print global c              (1)
console.log(b);        // Print returned value        (9)
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132