0
0
Javascriptprogramming~5 mins

Why conditional logic is needed in Javascript

Choose your learning style9 modes available
Introduction

Conditional logic helps a program make decisions. It lets the program choose what to do based on different situations.

When you want to check if a user is logged in before showing content.
When you need to decide what message to show based on a user's age.
When you want to perform different actions depending on the day of the week.
When you want to check if a number is positive, negative, or zero.
When you want to handle errors differently depending on the problem.
Syntax
Javascript
if (condition) {
  // code to run if condition is true
} else {
  // code to run if condition is false
}
The condition is a question that can be true or false.
The code inside the if block runs only if the condition is true.
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 message to show depending 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 the time and prints a greeting based on whether it is before noon or not.

Javascript
const hour = 10;

if (hour < 12) {
  console.log('Good morning!');
} else {
  console.log('Good afternoon!');
}
OutputSuccess
Important Notes

Conditional logic is like asking a question and choosing what to do next.

You can add more conditions using else if for more choices.

Summary

Conditional logic lets programs make choices.

It uses if and else to run different code based on conditions.

This helps programs respond to different situations.