scope - Surprised that global variable has undefined value in JavaScript -
today, got surprised when saw global variable has undefined
value in case.
example:
var value = 10; function test() { //a console.log(value); var value = 20; //b console.log(value); } test();
gives output as
undefined 20
here, why javascript engine considering global value undefined
. know javascript interpreted language. how able consider variables in function?
is pitfall javascript engine?
this phenomenon known as: javascript variable hoisting.
at no point accessing global variable in function; you're ever accessing local value
variable.
your code equivalent following:
var value = 10; function test() { var value; console.log(value); value = 20; console.log(value); } test();
still surprised you're getting undefined
?
explanation:
this every javascript programmer bumps sooner or later. put, whatever variables declare hoisted top of local closure. so, though declared variable after first console.log
call, it's still considered if had declared before that.
however, declaration part being hoisted; assignment, on other hand, not.
so, when first called console.log(value)
, referencing locally declared variable, has got nothing assigned yet; hence undefined
.
here's another example:
var test = 'start'; function end() { test = 'end'; var test = 'local'; } end(); alert(test);
what think alert? no, don't read on, think it. what's value of test
?
if said other start
, wrong. above code equivalent this:
var test = 'start'; function end() { var test; test = 'end'; test = 'local'; } end(); alert(test);
so global variable never affected.
as can see, no matter put variable declaration, hoisted top of local closure.
side note:
this applies functions.
consider this piece of code:
test("won't work!"); test = function(text) { alert(text); }
which give reference error:
uncaught referenceerror: test not defined
this throws off lot of developers, since this piece of code works fine:
test("works!"); function test(text) { alert(text); }
the reason this, stated, because assignment part not hoisted. in first example, when test("won't work!")
run, test
variable has been declared, has yet have function assigned it.
in second example, we're not using variable assignment. rather, we're using proper function declaration syntax, does function hoisted.
ben cherry has written excellent article on this, appropriately titled javascript scoping , hoisting.
read it. it'll give whole picture in full detail.
Comments
Post a Comment