Here is a quick tip for JavaScript falsy conditions for programmers or for people who come from Java or C#.
In Java and C# when we thinks of using a compare conditions in a if statements, we tend to use something along the line of:
if(val != null && val.length > 0) {
//do stuff
}
We tend to bring this baggage of knowledge to JavaScript also, but it is not necessary. In JavaScript one can simply use the conditionals as below.
if(val) {
//do something
}
Here is a table that will show you what could be the values of val that would translate to false.
Type | Result |
---|---|
Undefined | false |
Null | False |
String | if length == 0, false |
Object | true |
Number | if NAN or 0, false |
Here is some sample code if you wish to test out falsy in JavaScript.
function testFalsy(val) {
if(val) {
console.log("True");
} else {
console.log("Falsy");
}
}
testFalsy(true); // Output: True
testFalsy({}); // Output: True
testFalsy([]); // Output: True
testFalsy("hello world"); // Output: True
testFalsy(3.14); // Output: True
testFalsy(new Date()); // Output: True
testFalsy(false); // Output: Falsy
testFalsy(null); // Output: Falsy
testFalsy(undefined); // Output: Falsy
testFalsy(NaN); // Output: Falsy
testFalsy(0); // Output: Falsy
logTruthiness(""); // Output: Falsy
Learning these fundamental idioms in JavaScript allows one to write cleaner Javascript code.