if...else Statement — JS Technical Interview Questions & Answers

Branching logic based on a condition.

if...else Statement

  • Branching logic based on a condition.
  • if...else Statement is JavaScript control flow. if / switch pick a branch. for / while repeat. Condition must be boolean-ish: if (marks >= 40). Use === not =.
  • for (let i = 0; i < arr.length; i++) or for (const m of marks). while needs a change inside or it loops forever.
  • Trap: = inside if. Trap: off-by-one on the last index.

Technical Interview Tip: if...else Statement: tiny marks example, predict the path.

Code Examples for if...else Statement

if...else Statement — working example

const marks = 72;
let grade;
if (marks >= 75) grade = "A";
else if (marks >= 50) grade = "B";
else grade = "C";

const day = 2;
let name;
switch (day) {
  case 1: name = "Mon"; break;
  case 2: name = "Tue"; break;
  default: name = "?";
}

const status = marks >= 50 ? "pass" : "fail";
console.log(grade, name, status);

if...else Statement — if/else and switch pick branches; ternary is a compact expression form of if/else.

How to Explain if...else Statement to an Interviewer

When if...else Statement?

To branch or repeat Show one small snippet