Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Conditions and conditional control flow

Conditions let you choose which code runs based on an expression's Boolean interpretation. Learn if, else if, and else, truthy/falsy conversion, and the distinction between a conditional statement and the ?: operator.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

if (condition) {
  statements;
} else if (otherCondition) {
  otherStatements;
} else {
  fallbackStatements;
}
const result = condition ? valueIfTrue : valueIfFalse;

Conditional control flow (conditional control flow) selects a program branch based on a condition. An if statement evaluates its condition and converts the result to a Boolean using ToBoolean. For true, it executes the first branch; otherwise, it executes the optional else branch. The unselected branch does not execute.

An else if chain checks successive conditions only until the first true condition; if none matches, it executes the final else, if provided. Several separate if statements can instead execute several branches. Use braces {} to make each branch's boundaries explicit.

A condition need not have type Boolean. Falsy values are false, undefined, null, 0, -0, NaN, 0n, and ""; other values are truthy, including "false", [], and {}. The historical browser exception is document.all, which is falsy. Use === and !== to compare without type conversion; = assigns a value rather than comparing.

The operator condition ? valueIfTrue : valueIfFalse is an expression selecting a value, rather than a statement selecting a block. It evaluates only the selected alternative. In the example, score equal to 72 produces grade equal to "B" and status equal to "pass". The if and ?: constructs have been part of ECMAScript since its first edition; the example requires no browser API.

Examples

const score = 72;
let grade;

if (score >= 90) {
  grade = "A";
} else if (score >= 60) {
  grade = "B";
} else {
  grade = "C";
}

const status = score >= 60 ? "pass" : "fail";
console.log(grade + ": " + status);

Result

B: pass

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources