JavaScript / 5 MIN READ
if statements
Master basic conditional logic in JavaScript
From the original Fervor library. Examples may use older package versions.
If statements
If statements are a foundational concept in any programming language, including JavaScript. They are used to perform different actions based on different conditions. Let’s take a look at their basic structure:
if (condition) {
// Code to execute if the condition is true
}
Here’s how it works:
- The condition inside the parentheses
(condition)is evaluated. - If the condition is true, the code block inside the curly brackets
{}is executed. - If the condition is false, the code block is skipped.
Here’s a concrete example:
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
In this case, since age is 18, the condition age >= 18 is true, so “You are eligible to vote.” is logged to the console.
Often, you’ll also see else and else if used in conjunction with if. These allow for additional, different conditions and a fallback if none of the conditions are met.
let age = 16;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not old enough to vote.");
}
In this case, the user’s age is 16, so the condition age >= 18 is false, and the code inside the else block is executed instead.
Else if can be used to add more conditions:
let age = 65;
if (age >= 18 && age < 65) {
console.log("You are eligible to vote and work.");
} else if (age >= 65) {
console.log("You are eligible to vote and retire.");
} else {
console.log("You are not old enough to vote.");
}
In this case, the first condition age >= 18 && age < 65 is false, but the second condition age >= 65 is true, so “You are eligible to vote and retire.” is printed to the console. If none of the conditions in the if or else if statements are met, the code in the else block will be executed.
Remember that the conditions are evaluated in order, and as soon as one condition is met, the corresponding block of code is executed and the rest of the conditions are ignored. That’s why the order of your conditions can be important.
Bonus IF (guard clauses)
Another interesting and somewhat “cool” thing you can do with if statements is a technique known as “guard clauses”.
Guard clauses are essentially conditional statements (usually if statements) that are used to prevent further execution of a function if certain conditions aren’t met. They’re called “guard” clauses because they “guard” the function against invalid input or state.
For example, consider a function that calculates the square root of a number:
function squareRoot(number) {
if (number < 0) {
console.log("Error: number must be non-negative.");
return;
}
return Math.sqrt(number);
}
In this case, the if statement at the top of the function is a guard clause. If the number is negative, the function logs an error and immediately returns, preventing the rest of the code (in this case, Math.sqrt(number)) from being executed with invalid input.
The use of guard clauses can often make your code cleaner and easier to understand. Instead of wrapping your entire function in an if...else statement, you can use a guard clause to handle the “unhappy” path and then proceed under the assumption that the input is valid, like so:
function processArray(array) {
if (!Array.isArray(array)) {
console.log("Error: input must be an array.");
return;
}
// Proceed under the assumption that array is indeed an array.
// ...
}
In this example, if the input is not an array, the function logs an error and returns. If the input is an array, the rest of the code executes without being wrapped in an else statement.
Using guard clauses can result in code that’s more readable and less nested, which can be very helpful in more complex functions.
Bonus how to use Truthy and Falsey
Let’s discuss a feature called “truthy” and “falsy” values in JavaScript, which can be used in clever ways with if statements.
In JavaScript, a value is either “truthy” or “falsy”. The following values are always falsy:
false
0(zero)''or""(empty string)nullundefinedNaN(Not a Number)
Everything else in JavaScript is considered truthy.
You can use this behavior to create very compact if statements. Here’s an example:
let username = getUsername();
if (!username) {
console.log("No username defined!");
}
In this case, if getUsername() returns null, undefined, an empty string, or any other falsy value, “No username defined!” will be logged to the console.
This can be particularly useful when dealing with optional properties of objects:
let user = {
firstName: "Alice",
// Note: no lastName property
};
if (!user.lastName) {
console.log("No last name specified!");
}
In this case, because the lastName property of user is undefined, “No last name specified!” is logged to the console.
Remember that this behavior can sometimes lead to unexpected results. For example, the number 0 and an empty string are both falsy, even though you might not always want to treat them as equivalent to false. Make sure you understand what values are truthy and falsy in JavaScript, and use this behavior carefully.