Saturday, May 11, 2024
13
rated 0 times [  20] [ 7]  / answers: 1 / hits: 18466  / 9 Years ago, thu, march 26, 2015, 12:00:00

My question is as title says;



What does this mean:



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


I mean if variable exist do something or what?


More From » if-statement

 Answers
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);
}

[#67308] Tuesday, March 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;