JavaScript Truth & Falsy Values

In JavaScript, every value is inherently either truthy or falsy.

Understanding truthy and falsy values is crucial when working with conditional statements and type coercion.

Let's delve into each aspect with code examples:

Truthy Values

Truthy values are values that evaluate to true when coerced to a boolean.

They are not necessarily the boolean value true, but they are considered truthy in boolean context.


if ("Hello!"){ 
  console.log("This will be executed.");
} 

if (42){ 
  console.log("So will this.");
}    

In the above example, both the string "Hello"and the number 42are truthy values. Therefore, the code blocks inside the ifstatements will be executed.

Example


if ("Hello!"){ 
  console.log("This will be executed.");
} 

if (42){ 
  console.log("So will this.");
}    

Falsy Values

Falsy values are values that evaluate to false when coerced to a boolean.

They include false, 0, ''(empty string), null, undefinedand NaN.


if (false){ 
  console.log("This will not be executed.");
} 

if (0){ 
  console.log("Neither will this.");
}    

In the above example, the boolean value falseand the number 0are falsy values. Therefore, the code blocks inside the ifstatements will not be executed.

Example


if (false){ 
  console.log("This will not be executed.");
} 

if (0){ 
  console.log("Neither will this.");
}    

Truthy and Falsy in Conditionals

Truthy and falsy values play a crucial role in conditional statements, where JavaScript performs type coercion to determine the truthiness or falsiness of a value.


let num = 10;

if (num){ 
  console.log("num is truthy.");
} else { 
  console.log("num is falsy.");
}    

In the above example, numhas a value of 10, which is truthy. Therefore, the code block inside the ifstatements will be executed.

Example


let num = 10;

if (num){ 
  console.log("num is truthy.");
} else { 
  console.log("num is falsy.");
} 

Type Coercion

JavaScript performs type coercion when evaluating conditions, converting non-boolean values to boolean as necessary.


console.log(Boolean("Hello")); // Output: true

console.log(Boolean(0)); // Output: false

In the above example, Boolean()is used to explicitly coerce values to boolean. The string "Hello"is coerced to true, while the number 0is coerced to false.

Example


console.log(Boolean("Hello")); // Output: true

console.log(Boolean(0)); // Output: false