LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 5 of 25

Conditional Statements Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Conditional Statements · Study material

Every program makes decisions, and conditional statements are how JavaScript makes them. They look simple, but they are a favourite for output questions because of a few sharp edges: an if condition is converted to a boolean (so "0" and [] are true), switch compares with ===, a missing break falls through to the next case, an else belongs to the nearest if, and the order of an else-if ladder decides the result. This topic covers all of them, plus guard clauses and lookup tables used in professional code. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

if, else and the else-if ladder

if (condition) { … } else if (other) { … } else { … } tests the conditions from top to bottom and runs only the first branch whose condition is true. Put the most specific (or highest) test first: checking marks >= 40 before marks >= 90 would give every topper a C.

// Only the FIRST condition that is true runs; the order of the tests matters
function grade(marks) {
  if (marks >= 90) return "A+";
  else if (marks >= 75) return "A";
  else if (marks >= 60) return "B";
  else if (marks >= 40) return "C";
  else return "Fail";
}
console.log([95, 75, 62, 40, 12].map(grade).join(" "));

Output

A+ A B C Fail

Truthy and falsy conditions

The condition can be any value; JavaScript converts it with Boolean(). The falsy values are false, 0, -0, 0n, "", null, undefined and NaN – everything else, including "0", "false", [] and {}, is truthy. Be careful when 0 or "" is a valid value: test count !== undefined or value != null instead of if (count).

// An if condition does not have to be a boolean: the value is converted with Boolean()
const inputs = ["", "Asha", 0, 42, null, [], {}];
for (const v of inputs) {
  if (v) console.log(JSON.stringify(v), "→ truthy");
  else console.log(JSON.stringify(v), "→ falsy");
}

Output

"" → falsy
"Asha" → truthy
0 → falsy
42 → truthy
null → falsy
[] → truthy
{} → truthy

switch

switch (value) compares the value with each case using strict equality (===) and starts running at the first match. Execution then continues through the following cases until a break, return or the end of the switch – this fall-through is how cases are grouped, and forgetting a break is a classic bug. default runs when no case matches; it may be written anywhere, but it is still tried last.

function dayType(day) {
  switch (day) {
    case "Sat":                 // grouped cases: an empty case falls through to the next one
    case "Sun":
      return "Weekend";
    case "Fri":
      console.log("(almost the weekend)");
      // no break or return: execution falls through into default
    default:
      return "Weekday";
  }
}
console.log(dayType("Sun"));
console.log(dayType("Fri"));
console.log(dayType("Mon"));

Output

Weekend
(almost the weekend)
Weekday
Weekday
// switch compares with === – no type conversion
const code = "1";              // e.g. read from a form field
switch (code) {
  case 1:
    console.log("number one");
    break;
  case "1":
    console.log("string one");
    break;
}

Output

string one

switch (true) for ranges

A switch cannot test ranges directly, but switch (true) compares true with each case expression, so the first case whose condition is true wins. An else-if ladder does the same job and is often clearer.

// switch (true): the first case whose expression is true wins – handy for ranges
const bmi = 27.4;
let category;
switch (true) {
  case bmi < 18.5: category = "Underweight"; break;
  case bmi < 25: category = "Normal"; break;
  case bmi < 30: category = "Overweight"; break;
  default: category = "Obese";
}
console.log(category);

Output

Overweight

The ternary operator

condition ? a : b is an expression, so it can be assigned, returned or used inside a template literal. Use it for a simple choice between two values; for actions or more than two outcomes, an if statement is more readable.

Guard clauses and early returns

Instead of nesting if inside if, handle invalid cases first and return immediately. The main logic then sits at the end, un-indented. This style is expected in professional code reviews.

// Guard clauses: reject bad cases first and return early – no deep nesting
function withdraw(balance, amount) {
  if (typeof amount !== "number" || amount <= 0) return "Invalid amount";
  if (amount > balance) return "Insufficient balance";
  if (amount % 100 !== 0) return "Amount must be a multiple of 100";
  return `Dispensed ${amount}, balance ${balance - amount}`;
}
console.log(withdraw(5000, -50));
console.log(withdraw(5000, 7000));
console.log(withdraw(5000, 250));
console.log(withdraw(5000, 1500));

Output

Invalid amount
Insufficient balance
Amount must be a multiple of 100
Dispensed 1500, balance 3500

Lookup tables instead of long switches

When each case only maps an input to a value, an object (or a Map) is shorter, faster to extend and easy to test. Combine it with ?? for a default.

// An object lookup replaces a switch that only maps values to values
const SHIPPING = { standard: 40, express: 120, overnight: 250 };
function shippingCost(type) {
  return SHIPPING[type] ?? "Unknown shipping type";
}
console.log(shippingCost("express"), shippingCost("drone"));

Output

120 Unknown shipping type

Common mistakes

  • A semicolon after if (…) – the if controls an empty statement and the block always runs.
  • = instead of === in a condition – it assigns, and the result is usually truthy.
  • Forgetting break – execution falls through into the next case.
  • Wrong ladder order – a broad test placed first catches everything.
  • switch on a string from input with number cases – === never matches "2" with 2.
  • if (count) when 0 is valid – 0 is falsy.
  • No braces with nested ifs – the else attaches to the nearest if.

Key points to remember

  • Only the first true branch of an if / else-if chain runs.
  • Conditions are converted to booleans: eight falsy values, everything else truthy.
  • switch uses ===; without break it falls through.
  • default can be anywhere but is chosen only when nothing matches.
  • An else pairs with the nearest unmatched if – always use braces.
  • The ternary is an expression; if is a statement.
  • Prefer guard clauses and lookup tables to deep nesting and huge switches.

Frequently asked questions

Is switch faster than if…else?

For a handful of cases there is no meaningful difference. Choose the clearer one: switch for many fixed values of one variable, if…else for ranges and mixed conditions, an object lookup for value-to-value mapping.

Can a switch case use expressions?

Yes. Each case expression is evaluated in order until one matches with ===, which is what makes switch (true) work.

Should I use the ternary operator?

For short value choices, yes. Avoid nesting more than one level deep; it quickly becomes unreadable.

Where can I learn more?

Read if, else and switch and JavaScript Operators in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links