In JavaScript, Truthy expressions evaluate to boolean true value and Falsy expressions evaluate to boolean false value.
Unlike other programming languages, truthy and falsy values are not limited to boolean data types and comparisons. They can have many other forms.
Let us learn what makes an expression truthy or falsy in JavaScript.
1. Falsy Expressions
There are total 6 falsy values/expressions in JavaScript. We will use testTruthyFalsy() function to check if a given value is truthy or falsy.
function testTruthyFalsy (val)
{
return val ? console.log('truthy') : console.log('falsy');
}
| Falsy Value/Expression | Description |
|---|---|
boolean ‘false‘ |
Boolean false is false.
testTruthyFalsy (false); //Prints 'falsy' |
Empty string i.e. '' |
Any empty string is evaluated to false.
testTruthyFalsy (''); //Prints 'falsy'
|
undefined |
Any undefined variable is equal to false.
var my_var = undefined; testTruthyFalsy (my_var); //Prints 'falsy' |
null |
Any null variable is equal to false.
var my_var = null; testTruthyFalsy (my_var); //Prints 'falsy' |
NaN |
Any numerical expression with result in NaN (not a number) is equal to false.
testTruthyFalsy (NaN); //Prints 'falsy' |
Number zero i.e. +0 or -0 |
Any numerical expression with result in zero is equal to false.
testTruthyFalsy ( 2 - 2 ); //Prints 'falsy' testTruthyFalsy ( 0 ); //Prints 'falsy' |
2. Truthy Expressions
Any expression or value, other than the above listed falsy values, is considered truthy.
function testTruthyFalsy (val)
{
return val ? console.log('truthy') : console.log('falsy');
}
testTruthy(true); // truthy
testTruthy(false); // falsy
testTruthy(new Boolean(false)); // truthy (object is always true)
testTruthy(''); // falsy
testTruthy('Packt'); // truthy
testTruthy(new String('')); // true (object is always true)
testTruthy(1); // truthy
testTruthy(-1); // truthy
testTruthy(NaN); // falsy
testTruthy(new Number(NaN)); // truthy (object is always true)
testTruthy({}); // truthy (object is always true)
var obj = { name: 'John' };
testTruthy(obj); // truthy
testTruthy(obj.name); // truthy
Happy Learning !!
Comments