why this javascript code snippet, outerString output ”undefined“? -
var outer = 'outer'; function fn1() { var outerstring = outer; var outer = 'inner'; console.log( outerstring ); console.log( outer ); } fn1();
why outerstring; // undefined?
three things going on here:
the
var outer
inside function shadowing (hiding)outer
variable you've declared outside function.this happens before
var outer
in function, becausevar
hoisted top of scope it's written (so function declarations).when variable created, starts out value
undefined
. looks variable initialization (var x = 42
) assignment happens later when step-by-step code runs.
your code looks javascript engine:
var outer; // global declaration `outer` function fn1() { // function declaration `fn1` var outerstring; // local decl `outerstring` var outer; // local decl `outer`, shadows (hides) global 1 // here, both outerstring , outer = `undefined` outerstring = outer; // no-op, they're both `undefined` outer = 'inner'; // give inner `outer` value `'inner'` console.log( outerstring ); // "undefined" console.log( outer ); // "inner" } outer = 'outer'; // note happens after declarations fn1(); // call function
more (on blog): poor, misunderstood var
Comments
Post a Comment