0
0
Javascriptprogramming~5 mins

If statement in Javascript

Choose your learning style9 modes available
Introduction

An if statement helps your program make decisions by running code only when certain conditions are true.

To check if a user is logged in before showing their profile.
To decide if a number is positive or negative and show a message.
To turn on a light only if it is dark outside.
To give a discount only if a customer buys more than 5 items.
Syntax
Javascript
if (condition) {
  // code to run if condition is true
}

The condition is a question your program asks, like 'Is it raining?'.

If the condition is true, the code inside the curly braces runs. If false, it skips.

Examples
This checks if age is 18 or more, then prints a message.
Javascript
if (age >= 18) {
  console.log('You can vote');
}
This runs the message only if the temperature is below zero.
Javascript
if (temperature < 0) {
  console.log('It is freezing');
}
This runs if the variable isRaining is true.
Javascript
if (isRaining) {
  console.log('Take an umbrella');
}
Sample Program

This program checks if the score is 60 or more. If yes, it prints a congratulation message.

Javascript
const score = 75;

if (score >= 60) {
  console.log('You passed the test!');
}
OutputSuccess
Important Notes

Always use parentheses () around the condition.

Curly braces {} group the code that runs when the condition is true.

If the condition is false, the code inside the if block is skipped.

Summary

An if statement runs code only when a condition is true.

Use it to make your program decide what to do next.

Remember to put the condition in parentheses and the code to run inside curly braces.