简体   繁体   中英

What does this mean: if( variable ){ /* do something */ }

My question is as title says;

What does this mean:

if( variable ){ /* do something */  }

I mean if variable exist do something or what?

It means if variable is truthy , then execute the block. In JavaScript, the following are falsey

  • false
  • 0
  • NaN
  • undefined
  • null
  • "" (Empty String)

Other than the above, everything else is truthy , that is, they evaluate to true .

If the variable didn't exist at all (that is, it had never been declared), that could would throw a ReferenceError because it's trying to read the value of a variable that doesn't exist.

So this would throw an error:

if (variableThatDoesntExist) {
    console.log("truthy");
}

This would log the word "truthy":

var variable = "Hi there";
if (variable) {
    console.log("truthy");
}

And this wouldn't log anything:

var variable = "";
if (variable) {
    console.log("truthy");
}

It's Javacript syntax to check if the variable is truthy or falsy .

It's similar to saying if (variable is true) { /* Do something */}

In Javascript, these are falsy values.

  1. false
  2. 0 (zero)
  3. "" (empty string)
  4. null
  5. undefined
  6. NaN (Not-a-Number)

All other values are truthy, including "0" (zero as string), "false" (false as a string), empty functions, empty arrays, and empty objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM