How to check if a variable is not null?

How to check if a variable is not null?

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

Should I do:

if (myVar) {...}

or

if (myVar !== null) {...}

回答1

They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.

The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):

  • null
  • undefined
  • 0
  • "" (the empty string)
  • false
  • NaN

 

 

回答2

  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

https://dorey.github.io/JavaScript-Equality-Table/

 

posted @ 2021-01-04 10:44  ChuckLu  阅读(111)  评论(0编辑  收藏  举报