Defining JavaScript variables inside if-statements

前端 未结 5 1130
悲&欢浪女
悲&欢浪女 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:45

    See function four on What is the scope of variables in JavaScript?

    As of 2012, there's no block-level scope in JavaScript. So your first version is fine: the variables are defined in the scope outside the if block.

提交回复
热议问题