By the end of this lesson, you will understand truthy values, falsy values, and strict equality in JavaScript.
In JavaScript, some values are considered truthy and some are considered falsy. Truthy values are those that evaluate to true in a boolean context. Falsy values are those that evaluate to false. For example, 0, “” (empty string), null, undefined, and false are falsy. Every other value is truthy. Think of a light switch. When it’s off (falsy), the light doesn’t work. When it’s on (truthy), the light shines.
In JavaScript, the strict equality operator === checks if two values are equal and of the same type. For example, 5 === "5" will return false because a number is being compared to a string, even though they look similar.
File: truthy-falsy.php
let value1 = 0; // Falsy value
let value2 = "Hello"; // Truthy value
if (value1) {
console.log("Value1 is truthy");
} else {
console.log("Value1 is falsy");
}
if (value2 === "Hello") {
console.log("Value2 is strictly equal to 'Hello'");
}
Value1 is falsy
Value2 is strictly equal to 'Hello'
The first if statement checks value1, which is falsy. Thus, it goes to the else block and prints “Value1 is falsy”. The second if checks if value2 strictly equals “Hello”. It evaluates to true, and prints the corresponding message.
Create a program that checks if a user input is falsy or truthy. Use a prompt to get input from the user. Display a message based on the input.
let userInput = prompt("Enter something:");
if (userInput) {
alert(userInput + " is truthy!");
} else {
alert(userInput + " is falsy!");
}