Search code examples
javascriptscopeclosureslexical-scope

Lexical scope in javascript function


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?


Solution

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