Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How JS engine treat variable declaration in Condition block?

Tags:

javascript

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

like image 580
Kuan Avatar asked Jun 22 '26 04:06

Kuan


2 Answers

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.

like image 191
TbWill4321 Avatar answered Jun 24 '26 17:06

TbWill4321


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.

like image 20
Rick Hitchcock Avatar answered Jun 24 '26 18:06

Rick Hitchcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!