Falsy and Truthy in JS
Difference between == and ===
In a word, == tries to covert the two values to the same type, and then compare its value.
1 | "10" == 10; //true |
But === requires the two values to have the same value and the same type:
1 | "10" === 10; //false |
== is not so safe to use, so we usually use === or !==.
How to determine if a value is true or false
In JS, whenever we need to transfer a value into a boolean, the value will be determined as truthy or falsy.
It is most commonly used in logical operators like and &&, or ||, not !. When a value is considered truthy it will be converted into true for comparison, vice versa.
Generally speaking, there are only 7 values that will be considered as falsy:
falsethe boolean value false0number zero-0negative 00nthe bigInt zero""/''empty stringnullundefinedNaNnot a number
All other values are considered truthy!
If you are not sure if the value is truthy or not, you can use type conversion to find out:
1 console.log(Boolean("0")); //true
However, there are some weird behaviors we may need to memorize:
NaNis NOT equal to anything including itself, so we can only useisNaNto check its type:1
2
3console.log(NaN == NaN); //false
console.log(Number.isNaN(10/0)); //true
console.log(typeof NaN); //"number"nullcan only be assigned when the programmer explicitly set the value asnull, if the variable have no value when declared, it will beundefined.1
2
3
4console.log(typeof null); //object
console.log(typeof (undefined)); //undefined
console.log(null === undefined); //false
console.log(null == undefined); //true, cause they are all falsy
Short Circuiting
Apart from using &&, || in if or while loop, we can also use them in short circuiting to make things easier.
||OR: returns the first truthy value:It is very useful when we want to set a default value when the input is not valid.1
2
3const userName = '';
const defaultName = userName || 'Guest';
console.log(defaultName); // 'Guest'&&AND: returns the first falsy value1
console.log(0&&1); //1
??Nullish Coalescing Operator: Just like||, but only checksnullandundefined1
2
3
4console.log(null ?? 'default'); // 'default'
console.log(undefined ?? 'default'); // 'default'
console.log(0 ?? 42); // 0 ✅ (NOT replaced!)
console.log('' ?? 'default'); // '' ✅
With this logic, we can also use logical assignment operators:
1
2
3 a = 0;
a = a || 100;
a ||= 100; //they are the same

