-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Conditional statements are a cornerstone of programming. In JavaScript, the if...else statement allows developers to execute different blocks of code based on whether a condition evaluates to true or false. Understanding how to use if...else correctly is essential for controlling the flow of your applications, handling user input, validating data, and responding to dynamic conditions.
This tutorial provides a detailed explanation of if...else, practical examples, common mistakes, best practices, and real-world applications to ensure a comprehensive understanding.
Conditional statements are vital because they allow your code to make decisions. Without conditionals, your program would execute the same way regardless of inputs or states, making it static and inflexible. With if...else, you can:
React differently to user input or system events.
Validate forms, inputs, or data from APIs.
Build interactive features in web applications.
Handle errors or unexpected cases gracefully.
Control the flow of execution in a predictable manner.
For example, a login system uses conditionals to verify whether the user has provided correct credentials, while an e-commerce site might use them to check stock availability before completing a purchase.
The basic syntax of an if...else statement in JavaScript is:
if (condition) {
// Code to execute if the condition is true
} else if (anotherCondition) {
// Code to execute if anotherCondition is true
} else {
// Code to execute if none of the conditions are true
}
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
In this example, the message is logged only if the age variable is 18 or more.
let score = 45;
if (score >= 50) {
console.log("You passed!");
} else {
console.log("You failed.");
}
Here, if the score is 50 or more, the first block executes; otherwise, the second block runs.
let marks = 85;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 50) {
console.log("Grade C");
} else {
console.log("Fail");
}
This structure allows multiple conditions to be checked sequentially. Once a true condition is found, its block executes, and the rest are skipped.
Sometimes, you may need to make decisions within decisions. This is where nested if...else statements come into play:
let temperature = 25;
if (temperature > 30) {
console.log("It's hot outside.");
} else {
if (temperature >= 20) {
console.log("It's warm outside.");
} else {
console.log("It's cold outside.");
}
}
Nested statements allow for more granular control, but excessive nesting can reduce readability. In such cases, consider breaking logic into functions.
For simpler conditional checks, the ternary operator provides a compact alternative:
let age = 20;
let access = age >= 18 ? "Allowed" : "Denied";
console.log(access); // Allowed
The ternary operator follows the syntax: condition ? valueIfTrue : valueIfFalse. It’s best suited for simple, concise conditions rather than complex logic.
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
let username = "";
let password = "secret";
if (username === "") {
console.log("Username cannot be empty");
} else if (password.length < 6) {
console.log("Password must be at least 6 characters long");
} else {
console.log("Login successful");
}
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
let age = 16;
if (age >= 18) {
console.log("Access granted");
} else {
console.log("Access denied. You must be at least 18.");
}
let marks = 80;
let attendance = 90;
if (marks >= 50 && attendance >= 75) {
console.log("You are eligible for the exam");
} else {
console.log("You are not eligible for the exam");
}
let totalPurchase = 1200;
if (totalPurchase >= 1000) {
if (totalPurchase >= 2000) {
console.log("You get a 20% discount");
} else {
console.log("You get a 10% discount");
}
} else {
console.log("No discount available");
}
Using assignment = instead of comparison == or ===.
Forgetting curly braces {} for blocks, which can lead to executing unintended statements.
Overcomplicating nested if...else instead of using functions or switch for clarity.
Not considering all possible conditions, which may leave some cases unhandled.
Prefer === and !== for strict comparison to avoid unexpected type coercion.
Keep conditions simple and readable.
Use the ternary operator for simple true/false conditions.
For deeply nested logic, break it into functions or consider switch statements.
Always handle all possible scenarios to prevent undefined behavior.
User authentication systems
Form validation and error handling
Calculating grades, discounts, or pricing tiers
Dynamic content rendering based on time, location, or user input
Game logic for player actions, scoring, and levels
The if...else statement in JavaScript is a fundamental tool for implementing conditional logic. It allows you to respond to different scenarios, validate inputs, and control the flow of your applications. By combining if, else if, and else, and using best practices like strict comparisons, proper nesting, and ternary operators, you can write dynamic, readable, and reliable code. Understanding if...else is essential for building interactive and intelligent web applications.
Q1. How do you check if a number is positive using an if statement?
Q2. What message does this code print if score = 60?
if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Q3. How do you write an if...else if...else block to check grades A, B, or C?
Q4. What happens if no condition in if or else if is true?
Q5. Can you use comparison operators like >, <, == in an if condition?
Q6. What is the output if the if condition is false and there is no else block?
Q7. What values are considered falsy in an if statement?
Q8. How do you check if a user is logged in (e.g., isLoggedIn = true) before showing a message?
Q9. How does JavaScript handle non-boolean values in if conditions?
Q10. Write an if block to check if a string is not empty.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
