javascript - Accessing global variable defined inside a function -
i trying understand variable scopes in javascript , friend asked me question. use here.
function abc(){ var = b = 10; // local, b global variable. right? c = 5; // c global variable } d = 20; // d global variable console.log(b); // b not defined error. why? isn't b global variable? console.log(c); // again, why 'c not defined'.
i ran code in chrome console. shouldn't expect 10 , 5 in console? gives 'b not defined', 'c not defined' error instead. why happen if b, c global variables? console.log(d) works fine.
here's fiddle.
why happen if
b
,c
global variables?
b
, c
created if call abc
. merely defining function not magically execute body.
function abc(){ var = b = 10; // local, b global variable. c = 5; // c global variable } // call abc execute statements inside function abc(); console.log(b); // 10 console.log(c); // 5
that said, implicitly creating global variables not still. avoid globals if possible, , if not, explicitly declare them assigning global object (window
in browsers).
Comments
Post a Comment