5.Conditional expressions in JavaScript(if, else if, else)
Certainly! The if-else
statement is a fundamental control flow structure in JavaScript that allows you to execute different blocks of code based on a specified condition. Here's the basic syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Let's go through a few examples to illustrate how if-else
works:
Example 1: Checking if a Number is Positive or Negative
let number = 5;
if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is non-positive (zero or negative).");
}
Example 2: Checking if a User is Logged In
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in to continue.");
}
Example 3: Determining the Category of a Number
let score = 75;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("D");
}
Example 4: Checking Even or Odd
let num = 12;
if (num % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
Example 5: Nested if-else
for Multiple Conditions
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
These examples cover various scenarios, such as checking numbers, user authentication, grading, and time-based greetings. Understanding how to use if-else
statements is crucial for making decisions in your code based on different conditions. As you become more familiar with JavaScript, you'll find that if-else
statements are a powerful tool for controlling the flow of your programs.
ternary operator
A conditional expression in JavaScript is also known as the ternary operator. It provides a concise way to write an if-else
statement in a single line. The syntax of the ternary operator is as follows:
condition ? expression_if_true : expression_if_false;
Here's how it works:
condition
: An expression that evaluates to eithertrue
orfalse
.expression_if_true
: The value or expression to be returned if thecondition
istrue
.expression_if_false
: The value or expression to be returned if thecondition
isfalse
.
The ternary operator evaluates the condition
. If the condition
is true
, it returns the result of expression_if_true
; otherwise, it returns the result of expression_if_false
.
Here's an example:
let age = 20;
// Using the ternary operator to determine if a person is eligible to vote
let canVote = (age >= 18) ? "Yes, can vote" : "No, cannot vote";
console.log(canVote); // Output: "Yes, can vote"
In this example, age >= 18
is the condition. If age
is greater than or equal to 18, the expression returns "Yes, can vote"; otherwise, it returns "No, cannot vote."
Using the ternary operator can make your code more concise and readable in cases where you have simple conditional checks. However, it's important to use it judiciously, as overly complex expressions can reduce code readability.
Example 1: Checking Even or Odd
let number = 7;
let result = (number % 2 === 0) ? "Even" : "Odd";
console.log(result); // Output: "Odd"
In this example, the ternary operator checks if number % 2
is equal to 0. If true, it returns "Even"; otherwise, it returns "Odd." Since 7 % 2 is not equal to 0, the result is "Odd."
Example 2: Checking a Login
let isLoggedIn = true;
let loginMessage = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(loginMessage); // Output: "Welcome back!"
Here, the ternary operator checks the value of isLoggedIn
. If isLoggedIn
is true, it returns "Welcome back!"; otherwise, it returns "Please log in."
Example 3: Displaying a Greeting
let isMorning = false;
let greeting = isMorning ? "Good morning!" : "Good day!";
console.log(greeting); // Output: "Good day!"
The ternary operator checks the value of isMorning
. If isMorning
is true, it returns "Good morning!"; otherwise, it returns "Good day!"
Example 4: Setting a Default Value
let userInput = ""; // assume this is user input
let username = userInput || "Guest";
console.log(username); // Output: "Guest" (if userInput is an empty string)
In this example, if userInput
is a falsy value (in this case, an empty string), the ternary operator returns the default value "Guest."
Example 5: Checking Multiple Conditions
let temperature = 25;
let weather = (temperature > 30) ? "Hot" : (temperature > 20) ? "Moderate" : "Cold";
console.log(weather); // Output: "Moderate"
This example uses nested ternary operators to check multiple conditions. It first checks if temperature > 30
, then if temperature > 20
. If both conditions are false, it defaults to "Cold." In this case, temperature
is 25, so it falls into the "Moderate" range.
In Example 5, the ternary operator is nested to check multiple conditions. The first condition checks if the temperature is greater than 30, the second condition checks if it's greater than 20, and if both are false, it defaults to "Cold."
These examples showcase the versatility of the ternary operator for handling various conditional scenarios in a concise manner. Remember to use it appropriately to maintain code readability.
Subscribe to my newsletter
Read articles from Shofique Rian directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by