DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Conditional statements in JavaScript

Conditional statements in JavaScript allow you to perform different actions based on different conditions.

1. if, else if, and else

Executes a block of code if a condition is true.

let score = 75;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 70) {
  console.log("Grade: B"); // Executes this block
} else {
  console.log("Grade: F");
}
Enter fullscreen mode Exit fullscreen mode

2. Ternary Operator (? :)
A concise shortcut for simple if...else assignments.

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";

console.log(status); // "Adult"
Enter fullscreen mode Exit fullscreen mode

3. switch Statement
Evaluates an expression against multiple potential case matches using strict equality (===). Best when checking a single value against fixed options.

let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the work week!");
    break; // Stops execution from falling through to the next case
  case "Friday":
    console.log("Weekend is near!");
    break;
  default:
    console.log("Midweek day");
}
Enter fullscreen mode Exit fullscreen mode

4. Logical Operators in Conditions
Combine multiple conditions using logical operators:

  • && (AND): true only if both conditions are true.
  • || (OR): true if at least one condition is true.
  • ! (NOT): Inverts the boolean value.
let isAdult = true;
let hasTicket = false;

if (isAdult && hasTicket) {
  console.log("Allowed entry.");
} else {
  console.log("Entry denied."); // Executes this
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)