JavaScript - Conditional Statements
Last Updated :
21 Nov, 2024
JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.
1. Using if Statement
The if statement is used to evaluate a particular condition. If the condition holds true, the associated code block is executed.
JavaScript
let x = 20;
if (x % 2 === 0) {
console.log("Even");
}
if (x % 2 !== 0) {
console.log("Odd");
};
2. Using if-else Statement
The if-else statement will perform some action for a specific condition. Here we are using the else statement in which the else statement is written after the if statement and it has no condition in their code block.
JavaScript
let age = 25;
if (age >= 18) {
console.log("Adult")
} else {
console.log("Not an Adult")
};
3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating more than two options based on whether the conditions are true or false.
JavaScript
const x = 0;
if (x > 0) {
console.log("Positive.");
} else if (x < 0) {
console.log("Negative.");
} else {
console.log("Zero.");
};
Please refer JavaScript If-Else for more detailed explanation.
4. Using Switch Statement (JavaScript Switch Case)
As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we dealing with many conditions, the switch statement may be a more preferred option.
JavaScript
const marks = 85;
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}
console.log(`Student Branch name is : ${Branch}`);
OutputStudent Branch name is : Mechanical engineering
Please refer JavaScript Switch Statement for details
5. Using Ternary Operator ( ?: )
The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.
JavaScript
let age = 21;
const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";
console.log(result);
OutputYou are eligible to vote.
Please refer JavaScript Ternary Operator for more details
6. Nested if...else
Nested if...else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if...else statement. This nesting can continue to multiple levels, but it's important to maintain readability and avoid excessive complexity.
JavaScript
let weather = "sunny";
let temperature = 25;
if (weather === "sunny") {
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a warm day.");
} else {
console.log("It's a bit cool today.");
}
} else if (weather === "rainy") {
console.log("Don't forget your umbrella!");
} else {
console.log("Check the weather forecast!");
};
Summary
Conditional Statement | Description |
---|
if statement | Executes a block of code if a specified condition is true. |
else statement | Executes a block of code if the same condition of the preceding if statement is false. |
else if statement | Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested. |
switch statement | Evaluates an expression, then executes the case statement that matches the expression's value. |
ternary operator | Provides a concise way to write if-else statements in a single line. |
Nested if else statement | Allows for multiple conditions to be checked in a hierarchical manner. |
This table outlines the key characteristics and use cases of each type of conditional statement. Now let's understand each conditional statement in detail along with the examples.
Similar Reads
Control Statements in JavaScript
JavaScript control statement is used to control the execution of a program based on a specific condition. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition. Types of Control Statements
3 min read
JavaScript- Control Flow Statements
Control flow statements in JavaScript control the order in which code is executed. These statements allow you to make decisions, repeat tasks, and jump between parts of a program based on specific conditions.1. Decision-Making StatementsJavaScript if StatementThe if statement executes a block of cod
4 min read
JavaScript switch Statement
The JavaScript switch statement evaluates an expression and executes a block of code based on matching cases. It provides an alternative to long if-else chains, improving readability and maintainability, especially when handling multiple conditional branches.Switch Statement Example: Here, we will p
5 min read
How to Use AND Statement in if with JavaScript?
In JavaScript AND (&&) logical operator is used in the 'if' statement to check for two or more conditional validities. AND logical operator in the 'if' condition returns true only when all the conditions inside the 'if' statement are TRUE. If any one condition inside the 'if' statement is FA
2 min read
CoffeeScript Conditional Statements
The CoffeeScript programming language is used to write a simpler syntax that compiles into JavaScript before getting executed. In any programming language, conditions play an important role in the execution of code in a particular sequence. In this article, we will see various conditional Statements
5 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the
3 min read
How to Set Multiple Conditions in an If Statement in JavaScript?
In JavaScript, conditional statements like if are used to execute code blocks based on certain conditions. There are situations where we might want to check multiple conditions within a single if statement. In such cases, JavaScript provides logical operators like && (AND) and || (OR) to com
5 min read
JavaScript Comparison Operators
JavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. JavaScript// Illustration of (==) operator let x = 5; let y = '5'; // Checking of operands c
5 min read
JavaScript Control Flow Coding Practice Problems
Control flow structures like conditionals and loops design how JavaScript programs execute. Mastering if-else statements, switch cases, loops, and recursion is important for writing efficient code. This curated list of JavaScript control flow practice problems covers a variety of exercises to help y
1 min read
Javascript Short Circuiting Operators
In JavaScript, short-circuiting refers to the process of evaluating expressions from left to right and stopping as soon as the result is determined. If the outcome of an expression is clear before evaluating all conditions, the evaluation is âshort-circuited,â meaning the remaining conditions are ig
2 min read