JavaScript if/else Statement

JavaScript's If...Else statements are fundamental constructs that enable developers to create conditional logic, allowing the execution of different code blocks based on specified conditions. Here's a comprehensive explanation of If...Else statements with examples:

If Statement

The basic form starts with the if keyword, followed by a condition enclosed in parentheses. If the condition evaluates to true, the code block within the curly braces {} is executed.

let age = 18; if (age >= 18) { console.log("You are eligible to vote."); }

If...Else Statement

By extending the if statement with an else clause, you can provide an alternative code block to be executed when the condition evaluates to false.

Javascript if else statements
let age = 16; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are not eligible to vote yet."); }

If...Else If...Else Statement

To handle multiple conditions, you can use else if clauses between the initial if and the final else.

let score = 85; if (score >= 90) { console.log("You got an A."); } else if (score >= 80) { console.log("You got a B."); } else if (score >= 70) { console.log("You got a C."); } else { console.log("You need to improve your score."); }

Nested If...Else Statements

If...Else statements can be nested, allowing for more intricate conditional flows.

let time = 14; let isMorning = true; if (isMorning) { if (time < 12) { console.log("Good morning!"); } else { console.log("It's afternoon."); } } else { console.log("It's not morning."); }

Ternary Operator (Conditional Operator)

For concise conditional assignments, the ternary operator can be used as a shorthand.

let age = 20; let status = (age >= 18) ? "Adult" : "Minor"; console.log(status); // Output: "Adult"


If...Else statements form the backbone of decision-making in JavaScript, allowing developers to control the flow of their programs based on various conditions, ultimately enhancing the logic and interactivity of their applications.