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

前端 未结 7 658
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 11:49

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{
           


        
7条回答
  •  生来不讨喜
    2020-12-21 12:25

    I recommend doing this:

    var result = MORE_LIKELY_OUTCOME;
    
    if (LESS_LIKELY_CONDITION) {
        result = LESS_LIKELY_OUTCOME;
    }
    
    process(result);
    

    This way, you are setting result initially to what you are expecting it to be most of the times. Then, the if statement will change result if the condition occurs.

提交回复
热议问题