Nested conditional statements help you make decisions inside other decisions. This lets your program check many things step by step.
0
0
Nested conditional statements in Javascript
Introduction
When you want to check if a person is old enough and also if they have a ticket before entering a movie.
When you need to decide what to wear based on weather and time of day.
When you want to check if a number is positive, and if it is even or odd.
When you want to give different discounts based on customer type and purchase amount.
Syntax
Javascript
if (condition1) { if (condition2) { // code if both condition1 and condition2 are true } else { // code if condition1 is true but condition2 is false } } else { // code if condition1 is false }
You can put one if statement inside another to check multiple things.
Use curly braces { } to group the code inside each condition.
Examples
Check if someone is 18 or older, then check if they have a ticket.
Javascript
if (age >= 18) { if (hasTicket) { console.log('Allowed to enter'); } else { console.log('No ticket'); } } else { console.log('Too young'); }
Check if score is passing, then check if it is excellent.
Javascript
if (score >= 50) { if (score >= 90) { console.log('Grade A'); } else { console.log('Passed'); } } else { console.log('Failed'); }
Sample Program
This program decides what to do based on temperature and rain. If it's warm and not raining, go for a walk. If it's warm but raining, take an umbrella. Otherwise, stay inside.
Javascript
const temperature = 30; const isRaining = false; if (temperature > 20) { if (!isRaining) { console.log('Go for a walk'); } else { console.log('Take an umbrella'); } } else { console.log('Stay inside'); }
OutputSuccess
Important Notes
Indent your code inside each if or else block to keep it clear.
Too many nested conditions can be hard to read; consider other ways if it gets complicated.
Summary
Nested conditionals let you check one thing inside another.
Use them to make decisions that depend on multiple checks.
Keep your code clean and easy to read by using proper indentation.