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.
All other values are truthy, including "0" (zero as string), "false" (false as a string), empty functions, empty arrays, and empty objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With