0

The following snippet:

a = 0;

function f1() {
    a = 1;
    f2();
}

function f2() {
    return a;
}

f1();

returns undefined.

From what I understand, functions get access to variables when they're defined, and access the values of those variables when they're being executed. So, in this case I would've guessed f2 to have access to the global variable 'a', and read it's modified value (1). So why is it undefined?

tldr
  • 11,924
  • 15
  • 75
  • 120
  • The `return` in `f2` does not return from `f1`… But yes, all three `a`s refer to the same global variable. – Bergi May 26 '13 at 21:55

2 Answers2

5

You're not returning the result of the invocation of f2(), or anything else, in the f1 function, so f1 is correctly returning undefined.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • good catch! The function gets the value returned by its body, but it still has to return that to its caller. – tldr May 27 '13 at 00:17
0

Perhaps what you were after was the following:

a = 0; // variable a defined in the global scope and set to 0

function f1() {
    a = 1; // since a is declared without var,
           // sets the value of global variable a to 1
    return f2();
}

function f2() {
    return a; // since a was not declared with var,
              // return a from the global scope
}

alert(f1()); // displays the computed value 1 of a

Regards.

John Sonderson
  • 3,238
  • 6
  • 31
  • 45