JavaScript Conditional Statements

Conditional statements let your code take decisions: run one block if a condition is true, and another block if it is not.


if, else if and else

let marks = 75;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else if (marks >= 50) {
  console.log("Grade C");
} else {
  console.log("Fail");
}
Output of the above program is

Grade B

JavaScript checks the conditions from top to bottom and runs only the first block that is true.


switch

Use switch when you compare one value with many fixed options. Do not forget break, or the code continues into the next case.

let day = 3;
let name;

switch (day) {
  case 1:
    name = "Monday";
    break;
  case 2:
    name = "Tuesday";
    break;
  case 3:
    name = "Wednesday";
    break;
  default:
    name = "Another day";
}
console.log(name);
Output of the above program is

Wednesday


Ternary operator

let age = 20;
console.log(age >= 18 ? "Adult" : "Minor");
Output of the above program is

Adult


Truthy and falsy in conditions

let name = "";

if (name) {
  console.log("Hello " + name);
} else {
  console.log("Please enter your name");
}
Output of the above program is

Please enter your name

An empty string is falsy, so the else block runs. See Type Conversion.

Note: Use === in conditions and always write the curly braces, even for one line. It avoids bugs.

Summary

  • if / else if / else runs the first true block.
  • switch compares one value with many cases, and needs break.
  • The ternary operator is a short if/else.
  • Next: JavaScript Loops.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.