For this snippet, I'm not surprised global variable 'a' evaluates to be 5.
http://jsfiddle.net/MeiJsVa23/gZSxY/ :
var a = 10;
function func(){
a = 5;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // and this prints out 5 as expected. No surprise here.
But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5
never happened.
http://jsfiddle.net/MeiJsVa23/2WZ7w/ :
var a = 10;
function func(){
a = 5;
var a = 23;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // but this prints out 10!! why?
A code Snippet is a programming term that refers to a small portion of re-usable source code, machine code, or text. Snippets help programmers reduce the time it takes to type in repetitive information while coding. Code Snippets are a feature on most text editors, code editors, and IDEs.
This is due to variable hoisting: anything defined with the var
keyword gets 'hoisted' to the top of the current scope, creating a local variable a
. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With