6

My question is as title says;

What does this mean:

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

I mean if variable exist do something or what?

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Erdal SATIK
  • 573
  • 1
  • 6
  • 25

2 Answers2

17

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");
}
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
1

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.

Pramod Karandikar
  • 4,949
  • 6
  • 37
  • 60