Falsy values In JavaScript, falsy values are values that are considered false when evaluated in a boolean context. The following values are falsy in JavaScript:
false: The boolean value false.0: The number zero.''(empty string): An empty string.null: A special keyword denoting a null value.undefined: A special keyword denoting an undefined value.NaN: Not-a-Number, a special value representing an invalid numeric operation.
Here are some ways to tackle falsy values:
-
Use ! Negation to check for all falsy values If value is
false,0,'',null,undefined, orNaN, the condition is true, and the code inside the if block will execute. For example:if (!value) { // Do something }
-
Use Ternary or logical OR operators to provide default values for falsy values
const result = (value) ? value : defaultValue; const result = value || defaultValue;
-
Check for
nullandundefinedExplicitly: If you want to check specifically fornullorundefined, use strict equality:if (value === null || value === undefined) { // Handle null or undefined }