0
0
Javascriptprogramming~5 mins

Else–if ladder in Javascript

Choose your learning style9 modes available
Introduction

An else-if ladder helps you check many conditions one by one. It runs the code for the first true condition it finds.

When you want to choose between many options based on a value.
When you need to check different ranges of numbers and act differently.
When you want to handle multiple user inputs with different responses.
When you want to decide what message to show based on a score.
When you want to run different code depending on the time of day.
Syntax
Javascript
if (condition1) {
  // code to run if condition1 is true
} else if (condition2) {
  // code to run if condition2 is true
} else if (condition3) {
  // code to run if condition3 is true
} else {
  // code to run if none of the above conditions are true
}

Conditions are checked from top to bottom.

Only the first true condition's code runs, then the ladder stops.

Examples
This checks age and prints if the person is a child, teenager, or adult.
Javascript
let age = 20;
if (age < 13) {
  console.log('Child');
} else if (age < 20) {
  console.log('Teenager');
} else {
  console.log('Adult');
}
This assigns a grade based on the score using an else-if ladder.
Javascript
let score = 85;
if (score >= 90) {
  console.log('Grade A');
} else if (score >= 75) {
  console.log('Grade B');
} else if (score >= 50) {
  console.log('Grade C');
} else {
  console.log('Fail');
}
Sample Program

This program checks the temperature and prints a message about the weather.

Javascript
let temperature = 30;

if (temperature > 35) {
  console.log('It is very hot today.');
} else if (temperature > 25) {
  console.log('The weather is warm.');
} else if (temperature > 15) {
  console.log('It is a bit chilly.');
} else {
  console.log('It is cold outside.');
}
OutputSuccess
Important Notes

Make sure conditions do not overlap in a confusing way.

The else part is optional but useful for handling all other cases.

Summary

Use else-if ladder to check multiple conditions in order.

Only one block of code runs: the first true condition.

It helps make decisions with many options clearly and simply.