web - scope of the variable in JavaScript -


function foo(a) {   function a() {     return 8;   }   return a();   y = 9; } console.log(foo() + " " + y); 

this gives undefined error variable y.

function foo(a) {   y = 9;    function a() {     return 8;   }   return a(); } console.log(foo() + " " + y); 

this prints 8 9 in browser console.

if declare variable without var keyword becomes global variable.

why first function not follow idea?

it's because in first example, have return statement before y = 9 , assignment never reached, leaving undefined.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -