if Statement
In short: The simplest form of conditional branching — a code block only runs if a specified condition is true.
In more detail: With no associated else branch, nothing happens for a false condition, and the program continues with the next section of code. Only the combination with else or else…if allows deliberately reacting to the “otherwise” case as well.
In Depth
The condition of an if statement is always an expression that evaluates to a boolean (true/false) — in some languages (e.g. C), numbers are also implicitly converted for this (0 = false, anything else = true), while in strictly typed languages like Java or TypeScript, only a genuine boolean value is allowed.
if (condition) {
// only runs if condition == true
}A common beginner mistake is confusing assignment (=) with comparison (==/===) within the condition — in some languages (classically C), if (x = 5) compiles without complaint and assigns x the value 5, instead of comparing it with 5, which leads to hard-to-find bugs. Modern languages/linters warn about this or even forbid it syntactically.
For several independent conditions in a row, a deliberate distinction should be made between several separate if statements (every condition is always checked) and an else…if chain (only the first matching condition “wins”, the rest is skipped) — that’s a common but consequential logical difference.
Nested if statements are possible, but at three or more levels the code quickly becomes hard to read (a “pyramid of doom”) — this can often be avoided by returning early (return) from a function or by reformulating the condition (e.g. with logical operators).