Defining JavaScript variables inside if-statements

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

    Because JavaScript's variables have function-level scope, your first example is effectively redeclaring your variable, which may explain why it is getting highlighted.

    On old versions of Firefox, its strict JavaScript mode used to warn about this redeclaration, however one of its developers complained that it cramped his style so the warning was turned off. (Current versions of Firefox support a block-level variable declaration syntax.)

提交回复
热议问题