Javascript Truthy and falsy examples
- Admin
- Dec 31, 2023
- Javascript
Boolean in javascript always evaluates to true
or false
values.
It uses in boolean expressions such as conditional expressions and equality operators. In Other programming languages, boolean values are true and false .
In Javascript truthy and falsy values are not only true and false, but any data which evaluates to boolean expression.
truthy
- return true when resolved to true in boolean context falsy
- return false when resolved to false in boolean context
javascript falsey values examples
falsy
values are values that are false during the execution of the boolean expression.
The following are falsy
values.
- false
- NAN
- undefined
- null
- zero(0)
- -0
- biginteger(0n)
- empty string(""),”,“
- document.all
javascript truthy values examples
truthy
values are values that evaluate to true during the execution of the boolean expression.
- true
- []
- numbers
- ”0”, “false”, any strings
- Infinity
- -Infinity
- new Date()
Javascript truthy and falsy operation check example
truthy
and falsy
values use in conditional expression and equal operators.
Here is an example to check if condition
function isTrutyFalsy(arg) {
if (arg) {
console.log(arg + ": Truthy");
} else {
console.log(arg + ": falsy");
}
}
And the truthy examples.
isTrutyFalsy(134);
isTrutyFalsy(true);
isTrutyFalsy({});
isTrutyFalsy([]);
isTrutyFalsy(42);
isTrutyFalsy("0");
isTrutyFalsy("false");
isTrutyFalsy(new Date());
isTrutyFalsy(-15);
isTrutyFalsy(42n);
isTrutyFalsy(1.1);
isTrutyFalsy(-2.5);
isTrutyFalsy(Infinity);
isTrutyFalsy(-Infinity);
Output:
134: Truthy
true: Truthy
[object Object]: Truthy
: Truthy
42: Truthy
0: Truthy
false: Truthy
Mon Jan 03 2022 05:45:05 GMT+0000 (Coordinated Universal Time): Truthy
-15: Truthy
42: Truthy
1.1: Truthy
-2.5: Truthy
Infinity: Truthy
-Infinity: Truthy
falsy examples:
isTrutyFalsy("");
isTrutyFalsy("");
isTrutyFalsy(``);
isTrutyFalsy(0);
isTrutyFalsy(-0);
isTrutyFalsy(-0n);
isTrutyFalsy(false);
isTrutyFalsy(NaN);
isTrutyFalsy(null);
isTrutyFalsy(undefined);
Output:
: falsy
: falsy
: falsy
0: falsy
0: falsy
0: falsy
false: falsy
NaN: falsy
null: falsy
undefined: falsy
Javascript truthy and falsy checklist
Following is a table for truthy
and falsy
values in javascript boolean expressions.
Truthy | falsy |
---|---|
true | false |
numbers | 0,-0,0n |
,[] | "",”,“ |
“0”, “false”, any strings | NAN,undefined,null |
Infinity,-Infinity,new Date() | document.all |