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:

  1. the var outer inside function shadowing (hiding) outer variable you've declared outside function.

  2. this happens before var outer in function, because var hoisted top of scope it's written (so function declarations).

  3. 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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -