Can I set variables to undefined or pass undefined as an argument?

后端 未结 10 1888
北荒
北荒 2020-11-30 15:53

I’m a bit confused about JavaScript’s undefined and null values.

What does if (!testvar) actually do? Does it test for u

10条回答
  •  春和景丽
    2020-11-30 16:38

    You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

    You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

    The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

    To properly test for undefined or null, use these:

    if(typeof(testvar) === "undefined") { ... }
    
    if(testvar === null) { ... }
    

提交回复
热议问题