html - JavaScript scope conflicts -
i trying understand scope in javascript. if declare variable outside of function, global. hence tested following code understand sequence of execution. in following code, expected "demo1" take global value "volvo" since render text before declaring local variable same name inside function. surprise see value "undefined".
<!doctype html> <html> <body> <p id="demo"></p> <p id="demo1"></p> <p id="demo2"></p> <script> var carname = "volvo"; myfunction(); document.getelementbyid("demo").innerhtml = carname; function myfunction() { document.getelementbyid("demo1").innerhtml = carname; var carname = "volvo1"; document.getelementbyid("demo2").innerhtml = carname; } </script> </body> </html>
result:
volvo
undefined
volvo1
i modified further see happens if declare global variable inside function follows:
<!doctype html> <html> <body> <p id="demo"></p> <p id="demo1"></p> <p id="demo2"></p> <script> var carname = "volvo"; myfunction(); document.getelementbyid("demo").innerhtml = carname; function myfunction() { document.getelementbyid("demo1").innerhtml = carname; //declaring global variable carname = "volvo1"; document.getelementbyid("demo2").innerhtml = carname; } </script> </body> </html>
result:
volvo1
volvo
volvo1
this time "demo1" assumes global variable declared outside of function i.e "volvo".
can explain me?
in javascript called variable hoisting, defined as:
one of trickier aspects of javascript new javascript developers fact variables , functions "hoisted."
rather being available after declaration, might available beforehand.
that means the second var declaration of carname
variable excluding/eliminating first one inside function.
because if you declare variable var
keyword in global scope of code (beginning of code) , then re-declare same variable var keyword in scope(function, ...) second declaration exclude first one , variable value becomes undefined
.
edit:
you can see in variable hoisting section here impact of variable hoisting , difference between variable declaration , variable assignement:
all variable declarations hoisted (lifted , declared) top of function, if defined in function, or top of global context, if outside function.
it important know variable declarations hoisted top, not variable initialization or assignments (when variable assigned value).
Comments
Post a Comment