The use of undefined variables in if-statements

前端 未结 6 1741
别跟我提以往
别跟我提以往 2021-02-05 10:06

This snippet results in a JavaScript runtime error: (foo is not defined)

if (foo) {
    // ...
}

I have to define foo

6条回答
  •  太阳男子
    2021-02-05 10:38

    That would be because you're now defining it with:

    var foo = foo || null
    

    Why don't you define it in the first place? That seems pretty straightforward to me (unless I'm missing something).

    Using a variable before it's created (or set to something) is bad programming practice, and should be avoided. My advice is to not use that trick to ensure it is set to something but to track down the logic error and fix it.

提交回复
热议问题