JavaScript has a unique (and sometimes confusing) feature called Hoisting. Before explaining it let's take a quick quiz, what will be printed from the code below?
var x = 1;
function printX(){
console.log(x);
var x = 2;
};
printX();
var x = 1;
function printX(){
console.log(x);
var x = 2;
};
printX();
Well, you are thinking "This should print 1, but it looks like a trick, so I am going to say it will print 2". And you are not alone, this is a common Javascript pitfall.
To know the answer to this quiz, we need first to understand how javaScript executes code. When JavaScript starts to execute code it does so in two passes, the first pass it scans for all variable declarations and declare them with an undefined value. The second pass it executes the code (and this includes variable assignment). So for JavaScript engine the code above looks like this:
var x = 1;
function printX(){
var x;
console.log(x);
x = 2;
};
printX();
JavaScript considers the variable x inside the function scope as a totally different one from the x defined globally. Which means when x is printed, the value will be undefined.
function printX(){
var x;
console.log(x);
x = 2;
};
printX();
JavaScript considers the variable x inside the function scope as a totally different one from the x defined globally. Which means when x is printed, the value will be undefined.
No comments:
Post a Comment