Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpretation of var inside JavaScript if statement

Tags:

javascript

I have been taught to define variables at the top, regardless of their position in your code, as this is how JavaScript will interpret things. So, my understanding is that:

var foo = "Bob";

if (2 + 2 === 4) {
    var car = "Blah";
}

Will be interpreted like:

var foo = "Bob",
    car;

if (2 + 2 === 4) {
    car = "Blah";
}

Is my understanding correct? I've always tried to position my variable definitions at the top of the current scope, but sometimes those variables are only needed inside an if statement, so defining them outside seems a bit odd - is this still best practice?


1 Answers

Yes. var statements are hoisted (which is why best practise is to use them at the top of the function — it avoids confusion from people assuming block scope instead of function scope)

like image 142
Quentin Avatar answered Mar 01 '26 11:03

Quentin



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!