What Are JavaScript Conditionals? See Examples

Conditional statements in JavaScript are used to perform different actions based on different conditions. They help your program make decisions and execute specific code only when certain criteria are met.

This blog explains if, else, else if, and switch statements with examples.


1. The if Statement

The if statement executes a block of code only if a specified condition is true.

Syntax:

if(condition){
  // code to run
}

Example:

let age = 18;
if(age >= 18){
  console.log("You are an adult");
}

2. The else Statement

The else block runs if the condition in the if statement is false.

Syntax:

if(condition){
  // code if true
} else {
  // code if false
}

Example:

let age = 16;
if(age >= 18){
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}
// Output: You are a minor

3. The else if Statement

Used to check multiple conditions sequentially.

Syntax:

if(condition1){
  // code
} else if(condition2){
  // code
} else {
  // code
}

Example:

let score = 85;
if(score >= 90){
  console.log("Grade A");
} else if(score >= 75){
  console.log("Grade B");
} else {
  console.log("Grade C");
}
// Output: Grade B

4. The switch Statement

switch is used to perform different actions based on multiple possible values.

Syntax:

switch(expression){
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // code if no match
}

Example:

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("Other day");
}
// Output: Wednesday

5. Ternary Operator (Short Conditional)

The ternary operator provides a compact if-else.

Syntax:

condition ? valueIfTrue : valueIfFalse

Example:

let age = 20;
let canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // Yes

Conclusion

Conditional statements are essential in JavaScript for decision-making. Mastering if, else, else if, switch, and the ternary operator allows you to write dynamic, logical, and flexible programs.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *