Defining JavaScript variables inside if-statements

前端 未结 5 1138
悲&欢浪女
悲&欢浪女 2021-02-01 00:57

Is defining JavaScript variables inside if-statements correct?

if(a==1){
    var b = 1;
} else {
    var b = 0;
}

I know the code above will wo

5条回答
  •  暖寄归人
    2021-02-01 01:54

    Putting a var inside an if statement is not against "the rules" of the language, but it means that, because of var hoisting, that var will be defined regardless of whether the if statement's condition is satisfied.

提交回复
热议问题