DEV Community

kanaga vimala
kanaga vimala

Posted on

Today I Learned: Conditional Statements in JavaScript

JavaScript is one of the most widely used programming languages, and today I took my first steps into a key concept: conditional statements. These are used to perform different actions based on different conditions.

🧩 What Are Conditional Statements?

Conditional statements allow a program to make decisions. You can think of them like β€œif this happens, do that.”

In JavaScript, the most common conditional statements are:

  • if
  • else if
  • else
  • switch

βœ… if Statement

The if statement checks a condition. If it’s true, it runs a block of code.

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
}
Enter fullscreen mode Exit fullscreen mode

πŸ“ Output: You are an adult.


πŸ”„ else if and else

When you have more than one condition, you can use else if and else.

let time = 14;

if (time < 12) {
  console.log("Good morning!");
} else if (time < 18) {
  console.log("Good afternoon!");
} else {
  console.log("Good evening!");
}
Enter fullscreen mode Exit fullscreen mode

πŸ“ Output: Good afternoon!


πŸ” switch Statement

The switch statement is useful when you have many conditions based on the same variable.

let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Another day");
}
Enter fullscreen mode Exit fullscreen mode

πŸ“ Output: Wednesday


πŸ’‘ TIL Summary

  • Conditional statements control the flow of logic.
  • Use if for one condition, else if for multiple, and else for a fallback.
  • Use switch when checking the same variable for different values.

Top comments (0)