All:
I have one question about variable declaration, if I declare a variable in a if block, when JS engine meet that line, how does the engine know how to set that variable?
I know this is terrible way to declare variable, but just curious how JS engine works with it:
if( trueSituation ){
var a_variable = true;
}else {
var another_variable = false;
}
Thanks
Javascript has a term called 'variable hoisting'. When your code actually executes, all the vars get pulled to the top of the enclosing function:
function foo() {
var a_variable;
var another_variable;
if( trueSituation ) {
a_variable = true;
}else {
another_variable = false;
}
}
Prior to the if/else, you can console.log(a_variable) as the special value undefined.
As a side note, ES6 contains a construct called let that allows more traditional block scoping, however I believe it still hoists the variable to the top of the block.
In JavaScript, variable declarations are hoisted to the top of their containing scope.
So in your example, this:
if( trueSituation ){
var a_variable = true;
} else {
var another_variable = false;
}
… becomes this:
var a_variable, another_variable;
if( trueSituation ){
a_variable = true;
} else {
another_variable = false;
}
Both variables end up declared, but only one becomes defined based on the truthiness of trueSituation.
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