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:
|
1 2 3 |
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.
|
1 2 3 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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.



Leave A Comment