The use of undefined variables in if-statements

前端 未结 6 1744
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2021-02-05 10:33

    I find this a bit of a strange question. To answer it I think it's best to ask the question the other way round...

    What would be the expected result of

    if (foo) {
        // ...
    }
    

    where foo is not defined as a variable?

    I think the only possible answer is that the if would always evaluate to false and you'd never execute that block.

    Asking a more direct question to you, why would you expect code to work which refers to variables that don't exist and have not had values assigned? What is foo in the context you define above?

    Bottom line is that without the declaration the subsequent statement does not have any meaning. foo is not a term which can be evaluated on its own so you have to give the interpreter a context for the reference to foo so it can evaluate it.

    There are languages which automatically create variables for you when they are first assigned (python and VB share that dangerous trait) but even those will not be able to evaluate a variable prior to assignment, so the interpreters throw errors.

    If you had a compiler it would have told you about this too...

提交回复
热议问题