Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to declare a variable inside an if statement in Javascript?

Tags:

javascript

I have a Sublimelinter installed in Sublime Text 2 and it's great. However it doesn't like the following code:

if(condition){
    var result = 1;
}else{
    var result = 2;
}
process(result);

It says for var result = 2; that result is already defined and for process(result); that it's used out of scope. Is it just mistaking the {} of the if statement for a more closed scope or should I really be doing it like this:

var result;
if(condition){
    result = 1;
}else{
    result = 2;
}
process(result);
like image 836
Jake Avatar asked Nov 28 '25 02:11

Jake


1 Answers

No it is not "wrong"; it will get hoisted to the top of the nearest function definition, as per the ECMAScript specification.

Yes, your program "Sublimelinter" is incorrect to claim the variable is out of scope.

like image 150
ninjagecko Avatar answered Nov 30 '25 17:11

ninjagecko



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!