Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
Erdal SATIK Avatar asked Mar 26 '15 08:03

Erdal SATIK


2 Answers

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");
}
like image 91
Amit Joki Avatar answered Sep 28 '22 03:09

Amit Joki


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.

like image 20
Pramod Karandikar Avatar answered Sep 28 '22 04:09

Pramod Karandikar