The Wayback Machine - https://web.archive.org/web/20241001221017/https://www.geeksforgeeks.org/conditional-statements-in-javascript/
Open In App

Conditional Statements in JavaScript

Last Updated : 26 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

There are several methods that can be used to perform Conditional Statements in JavaScript.

Conditional StatementDescription
if statementExecutes a block of code if a specified condition is true.
else statementExecutes a block of code if the same condition of the preceding if statement is false.
else if statementAdds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
switch statementEvaluates an expression, then executes the case statement that matches the expression’s value.
ternary operatorProvides a concise way to write if-else statements in a single line.
Nested if else statementAllows 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.

JavaScript Conditional Statements Examples:

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.

Syntax:

if ( condition ) {
    // If the condition is met, 
    //code  will get executed.
}

Example: This JavaScript code determines if the variable `num` is even or odd using the modulo operator `%`. If `num` is divisible by 2 without a remainder, it logs “Given number is even number.” Otherwise, it logs “Given number is odd number.”

JavaScript
let num = 20;

if (num % 2 === 0) {
    console.log("Given number is even number.");
}

if (num % 2 !== 0) {
    console.log("Given number is odd number.");
};

Output
Given number is even number.

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.

Syntax:

if (condition1) {
    // Executes when condition1 is true
    if (condition2) {
        // Executes when condition2 is true
    }
}

Example: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it logs “You are eligible for a driving license.” Otherwise, it logs “You are not eligible for a driving license.” This indicates eligibility for driving based on age.

JavaScript
let age = 25;

if (age >= 18) {
    console.log("You are eligible of driving licence")
} else {
    console.log("You are not eligible for driving licence")
};

Output
You are eligible of driving licence

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.

Syntax:

if (1st condition) {
    // Code for 1st condition
} else if (2nd condition) {
    // ode for 2nd condition
} else if (3rd condition) {
    // Code for 3rd condition
} else {
    //  ode that will execute if all 
    // above conditions are false
}

Example: This JavaScript code determines whether the constant `num` is positive, negative, or zero. If `num` is greater than 0, it logs “Given number is positive.” If `num` is less than 0, it logs “Given number is negative.” If neither condition is met (i.e., `num` is zero), it logs “Given number is zero”.

JavaScript
const num = 0;

if (num > 0) {
    console.log("Given number is positive.");
} else if (num < 0) {
    console.log("Given number is negative.");
} else {
    console.log("Given number is zero.");
};

Output
Given number is zero.

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.

Syntax:

switch (expression) {
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    . . .
    case valueN:
        statementN;
        break;
    default:
        statementDefault;
};

Example: This JavaScript code assigns a branch of engineering to a student based on their marks. It uses a switch statement with cases for different mark ranges. The student’s branch is determined according to their marks and logged to the console.

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}`);

Output
Student Branch name is : Mechanical engineering

5. Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.

Syntax:

condition ? value if true : value if false

Example: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it assigns the string “You are eligible to vote.” to the variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value of `result` is then logged to the console.

JavaScript
let age = 21;

const result =
    (age >= 18) ? "You are eligible to vote."
        : "You are not eligible to vote.";

console.log(result);

Output
You are eligible to vote.

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.

Syntax:

if (condition1) {
    // Code block 1
    if (condition2) {
        // Code block 2
    } else {
        // Code block 3
    }
} else {
    // Code block 4
}

Example: In this example, the outer if statement checks the weather variable. If it’s “sunny,” it further checks the temperature variable to determine the type of day it is (hot, warm, or cool). Depending on the values of weather and temperature, different messages will be logged to the console.

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!");
};

Output
It's a warm day.


Similar Reads

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 such as If, Else, Else If, etc. that CoffeeScript
5 min read
How to use conditional statements with EJS Template Engine ?
Conditional statements in EJS templates allow you to dynamically control the content that is rendered based on specified conditions. Similar to JavaScript, EJS provides a syntax for using conditional logic within your HTML templates. In this article, we will see a practical example of using conditional statements with the EJS template. What are Con
3 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 code block inside it will be executed otherwise n
3 min read
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 in JavaScriptConditional Statement: These statemen
3 min read
JavaScript Statements
In JavaScript, a statement is like a complete instruction that tells the computer to do something. These statements are made up of different parts: Values, Operators, Keywords, Expressions, and Comments. Each statement is executed by the browser in the order it appears, line by line. Examples of JavaScript StatementsSemicolonsSemicolons are used to
3 min read
Web Search Bar Implementation Using Javascript Conditional Flow
Given a list of items and the task is to filter through the items and return the best match using the search bar. There are several approaches to implement this but, we will be using a simple if-else statement to implement our search bar. Approach:Create a folder called gfgSearchBar.Open the folder in your desired IDE or IDLE.Create a html file cal
2 min read
Why do Empty JavaScript Arrays Evaluate to True in Conditional Structures?
In JavaScript, there are situations when we need to evaluate whether a variable is "truthy" or "falsy" within conditional structures like if statements. While some values, like 0, null, undefined, and "" (empty string), are considered falsy and that should be the case, but empty arrays do not follow such instead they evaluate to true. The following
2 min read
How to Define an Array with Conditional Elements in JavaScript?
Sometime we may need to define an array with elements that depend on certain conditions. Such situation may occur when we have to dynamically generate arrays based on runtime logic such as including or excluding elements based on specific criteria. In this article, we'll explore various ways to define arrays with conditional elements in JavaScript.
2 min read
What is the use of curly brackets in the `var { ... } = …` statements ?
Destructuring assignment allows us to assign the properties of an array or object to a bunch of variables that are sometimes very convenient and short. Consider the following illustration. Both of the below-mentioned methods are right and produce the same result. Without Destructuring: var array = [1, 20, 40]; var first = array[0] var second = arra
2 min read
CoffeeScript | Statements
The syntax of CoffeeScript is simpler to JavaScript and can be easily learned if you have knowledge of JavaScript. It avoids the use of semicolons, curly braces, and variable declarations. CoffeeScript Statements: The statements of CoffeeScript do not end with semicolons (;). In this language, a new line is considered as a separate statement by the
3 min read
How to use if statements in Underscore.js templates ?
Underscore.js is a javascript library that provides helper functions in functional programming without extending the built-in objects. This package consists of 100 functions like map, filter, etc. We can install this by using npm. npm install underscore Syntax: const _ = require('underscore'); Approach: Write your markup code regarding the requirem
1 min read
How to use if, else and not statements in Ember.js ?
Ember.js is a framework for web development. It makes the process of development and prototyping faster with its tools. We can create dynamic web pages with it. Based on the dynamic data, we may or may not want to display some data or some UI or modify the UI. So we will learn to use If, Else and Not in an Ember.js application. Create the project S
3 min read
Simple way to condense if statements into a function to check arguments
In this article, we will try to understand how we use if statements inside a function in order to check the validity of the argument, and later we will see the simple way to condense(reduce) if statements into a function to check arguments as well as theoretical explanations in JavaScript. Let us first have a look into the following syntaxes (of ob
3 min read
TypeScript Interface vs Type Statements
In TypeScript, interface and type are used to define the structure of objects and custom types. While interfaces enforce contracts for classes and support multiple inheritance, types offer flexibility for defining complex and reusable type aliases. Each serves distinct use cases. Table of Content InterfaceType statementDifference between Interface
3 min read
CSS | Conditional Rules
CSS Conditional Rules are nothing but a feature of CSS in which the CSS style is applied based on a specific condition. So the condition here can be either true or false and based on the statements/style will get executed.These rules eventually come under CSS at-rule as they start with an @.The Conditional Rules are: @supports@media@document @suppo
2 min read
Vue.js Conditional Rendering
Vue.js is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Conditional Rendering in Vue makes
2 min read
How to use conditional operator in jQuery a template?
In this article, we will learn to use ternary or conditional operator in jQuery. The Ternary or Conditional operator takes three operands, a condition followed by question mark followed by two expressions to execute with a semicolon (:) in between the two expressions. Syntax: condition ? expression1 : expression2 Example: Now let us try an example
1 min read
Angular Conditional Class with *ngClass
In this article, we will see the basic implementation of the Conditional class with *ngClass in Angular, along with understanding their implementation with the help of examples. Conditional class with *ngClassAngular's *ngClass directive allows us to apply CSS classes conditionally to an element. It provides a convenient way to dynamically toggle c
5 min read
AngularJS ngClass Conditional
The ngClass is a directive in AngularJS that facilitates to implementation of the CSS classes on an HTML element dynamically, ie, by adding and removing CSS classes on that specific element. We can use the ngClass directive to provide certain conditions, to add different classes to the elements. In this article, we will see the multiple ways of app
2 min read
What are inline conditional expressions in ReactJS ?
In React conditional rendering is the process of showing components based on a particular condition. With inline conditional expression in React, we can write the condition in a single line. For example, While building the to-do list app, developers should show a task only if any pending task is available otherwise they can show a message like "The
4 min read
Conditional rendering component using Enums in ReactJS
In certain scenarios, a ReactJS developer may have to dynamically display or hide components depending on specific conditions. For instance, when creating a To-Do list application, the developer must render tasks if there are pending items; otherwise, they should display a message such as "No pending tasks available." Prerequisites:NodeJS or NPMRea
3 min read
How to handle Conditional Requests/Branching in Postman ?
Conditional requests or branching in Postman allows you to create logic within your requests to handle different scenarios based on conditions. This feature is useful for executing specific actions or tests depending on the response received from an API endpoint. In this article, we'll explore how to handle conditional requests or branching in Post
3 min read
What is the purpose of the && operator in conditional rendering?
The JavaScript conditional rendering concept allows you to display content in a dynamic way, based on predetermined conditions. The logic AND operator is often used to simplify code and improve readability for conditional rendering. This article will examine the purpose of && operator conditional rendering, and how to apply conditional rend
3 min read
What is a Conditional Statement in PHP?
A conditional statement in PHP is a programming construct that allows you to execute different blocks of code based on whether a specified condition evaluates to true or false. It enables you to create dynamic and flexible code logic by controlling the flow of execution based on various conditions. Conditional statements in PHP include:PHP conditio
2 min read
How to use Conditional Types in TypeScript ?
The conditional types in TypeScript are created using a condition that will only be created based on the condition check and its return value. They implement the extends keyword to check the condition and create a type based on the returned true or false value. The conditional types are mainly used to create flexible and generic type definitions. I
1 min read
React Conditional Rendering
React allows us to conditionally render components which means that the developer can decide which component to render on the screen on on the basis of some predefined conditions. This is known as conditional rendering. Table of Content Implementing Conditional Rendering 1. Conditional Rendering using if-else Statement2. Conditional Rendering using
5 min read
How to create conditional types in TypeScript ?
Conditional types in TypeScript enable defining types based on conditions, similar to conditional statements in code. They determine different types of values, making functions adaptable to various input types, and enhancing code flexibility and maintainability. Syntax: We can create conditional types with the used of the ternary operator and exten
3 min read
How to Implement a Generic Function with a Conditional Return Type ?
Implementing a generic function with a conditional return type involves creating a function that can accept multiple data types and return different types based on specified conditions. This allows for flexible behavior depending on inputs. The function's return type may vary dynamically, enhancing its versatility and utility in handling diverse sc
4 min read
Use of the Ternary Operator in Conditional Rendering.
In React, conditional rendering helps show different things based on certain conditions. The ternary operator is a concise way to do this quickly and clearly. In this article, we will learn step by step process to use the ternary operator for conditional rendering in React. Syntax: React developers have multiple approaches for implementing conditio
3 min read
How to implement Conditional Rendering in React?
This article explores JavaScript's conditional rendering in React JS, including various methods, syntax, and applications, leveraging React's virtual DOM, reusable components, props, and rapid rendering capabilities in single-page UI applications. We will use the following approaches to implement conditional rendering in React Table of Content if-e
4 min read