0
0
Javascriptprogramming~5 mins

If–else statement in Javascript

Choose your learning style9 modes available
Introduction

An if-else statement helps your program decide what to do based on a condition. It lets your code choose between two paths.

Checking if a user is logged in to show different content.
Deciding if a number is positive or negative.
Choosing what message to show based on the time of day.
Validating if a form input is filled or empty.
Syntax
Javascript
if (condition) {
  // code to run if condition is true
} else {
  // code to run if condition is false
}
The condition is a question your program asks that can be true or false.
The code inside the first block runs if the condition is true; otherwise, the code inside else runs.
Examples
This checks if age is 18 or more. It prints a message based on that.
Javascript
if (age >= 18) {
  console.log('You can vote');
} else {
  console.log('You are too young to vote');
}
This decides what to say based on the temperature.
Javascript
if (temperature > 30) {
  console.log('It is hot outside');
} else {
  console.log('It is not hot outside');
}
Sample Program

This program checks if a number is even or odd by using the remainder operator %. If the remainder when dividing by 2 is zero, it is even; otherwise, odd.

Javascript
const number = 10;

if (number % 2 === 0) {
  console.log('The number is even');
} else {
  console.log('The number is odd');
}
OutputSuccess
Important Notes

Always use curly braces {} to keep your code clear and avoid mistakes.

The condition inside if must result in true or false.

Summary

If-else lets your program choose between two actions.

The if block runs when the condition is true.

The else block runs when the condition is false.