Coding

Conditional Statements in Programming: If, Else, Switch, Match

Conditional statements in programming let a program run different code depending on whether a condition is true or false. The main forms are if, else if, else, a multi-way selector (switch or match), and the ternary operator.

The examples below use Python and JavaScript. The ideas carry over to C, Java, C# and most other languages, though the keywords and punctuation differ.

What is a conditional statement?

A conditional statement evaluates a condition, which is an expression that produces true or false, and chooses which code to run based on the result. Without conditionals, a program would execute the same steps in the same order every time. With them, it can check a password, reject a negative quantity, or pick a shipping rate.

Here is the smallest useful case in Python:

temperature = 31

if temperature > 30:
    print("Hot")

The block under if runs only when temperature > 30 is true. Here it is, so the program prints Hot. Python marks the block by indentation. JavaScript, C and Java use braces instead.

If, else if and else

Add else for the case where the condition is false, and else if to test further conditions in order. The first true condition wins and the rest are skipped. Python spells it elif. The Python tutorial describes the keyword as "short for 'else if'", and notes that it is useful to avoid excessive indentation.

score = 72

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(grade)

This prints C. The checks run top to bottom, so the order matters. A score of 95 is also greater than 70, but the first test already matched and the later ones never run. If you put score >= 70 first, every passing score would get a C.

JavaScript has no elseif keyword. MDN explains that you chain conditions by putting if after else:

if (x > 50) {
  // runs when x is above 50
} else if (x > 5) {
  // runs when x is 6 to 50
} else {
  // runs otherwise
}

Comparison and logical operators

Conditions are built from comparisons such as <, >= and ==, and combined with logical operators. Python writes them as and, or and not. JavaScript, C and Java use &&, || and !.

age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("Entry allowed")
else:
    print("Entry refused")

One language-specific trap: JavaScript has both == and ===. The double form converts types before comparing, so 1 == "1" is true. Most style guides prefer === for that reason.

What counts as true? Truthy and falsy values

In many languages the condition does not have to be a Boolean. JavaScript converts whatever you give it. According to MDN, the falsy values are false, undefined, null, 0, -0, 0n, NaN and the empty string "". Everything else is truthy, including all objects. MDN's example is a Boolean object wrapping false, which is still truthy because it is an object:

const b = new Boolean(false);
if (b) {
  console.log("b is truthy"); // runs
}

Rules differ by language, so check the rules of the language you are using before relying on shortcuts like if (name).

The dangling else and why braces help

If you leave out braces in a nested if, an else attaches to the nearest if, which is often not the one you meant. MDN shows this JavaScript example and recommends always using block statements:

function checkValue(a, b) {
  if (a === 1)
    if (b === 2)
      console.log("a is 1 and b is 2");
  else
    console.log("a is not 1");
}
// checkValue(1, 3) logs "a is not 1"

The indentation suggests the else belongs to a === 1, but it belongs to b === 2. With braces around each block, the meaning is explicit. Python avoids the problem because indentation is the syntax.

Switch and match: choosing between many fixed values

When one value is compared against a list of constants, a switch (C, Java, JavaScript) or match (Python) can read more clearly than a long else if chain. The Python tutorial says an if ... elif ... elif sequence is a substitute for the switch or case statements found in other languages. Python later added match, which the tutorial calls superficially similar to a switch statement but closer to the pattern matching in Rust or Haskell:

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

Only the first matching pattern runs. The name _ is a wildcard that never fails to match, so it works as the default branch. If no case matches and there is no wildcard, no branch runs.

The C family behaves differently: a switch falls through to the next case unless you end each one with break. Our guides cover the details for JavaScript and C.

The ternary operator: a conditional inside an expression

An if is a statement, so it does not produce a value. The conditional (ternary) operator is an expression, so it does. In JavaScript the syntax is condition ? exprIfTrue : exprIfFalse, and MDN notes it is the only JavaScript operator that takes three operands.

const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"

It suits short choices between two values. MDN also shows that it is right-associative and can be chained like an if ... else if ... else sequence, but once you have more than two outcomes, a normal if chain is usually easier to read. Python's equivalent is value_if_true if condition else value_if_false.

Which conditional should you use?

SituationUse
Run code only when something is trueif
Two outcomes, each with its own codeif / else
Ranges or several different tests, in priority orderif / else if (elif)
One value against several fixed constantsswitch or match
Pick one of two values inside an expressionTernary operator

Common mistakes

  • Wrong order of branches. Put the most specific condition first, as the grade example shows.
  • Assignment instead of comparison. In JavaScript, = assigns and === compares. Writing if (x = 5) assigns 5 to x and tests the result, so the branch always runs.
  • Missing braces in nested conditions. This causes the dangling else described above.
  • Forgetting the default branch. Add a final else or case _ so unexpected input is handled on purpose, not ignored.
  • Unreachable branches. If an earlier condition always catches a case, a later branch never runs. Test each branch with a value that should reach it.

Conditionals are often paired with loops. For that combination in Python, see Python for loop with if condition.

Frequently asked questions

What are the main types of conditional statements?
The common forms are the if statement, if with else, a chain of else if (elif in Python) branches, a multi-way selector (switch in C and JavaScript, match in Python), and the conditional or ternary operator, which picks one of two values inside an expression.
What is the difference between if and else if?
An if starts a decision. An else if (elif in Python) adds another condition that is checked only when every earlier condition was false. The first condition that is true runs, and the remaining branches are skipped. A plain else has no condition and runs when none of the others did.
When should I use switch or match instead of if?
Use it when one value is compared against several fixed alternatives, such as a status code or a command name. The intent is easier to read than a long else if chain. Use if for ranges, combined conditions, or tests on different variables.
Does JavaScript need a Boolean in an if condition?
No. JavaScript converts the condition to true or false. The falsy values are false, undefined, null, 0, -0, 0n, NaN and the empty string. Everything else is truthy, including every object.

Sources