Understand the idea
A condition chooses which code runs. An if statement evaluates an expression and executes its block when that expression is truthy.
Use === for strict equality when comparing values without type conversion. A single = assigns a value. A Boolean such as isOpen can be used directly as a condition. Braces keep the intended block clear even when it contains only one statement.
Read the example
This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.
const photographCount = 0;
if (photographCount === 0) {
console.log("No photographs yet.");
} else {
console.log("Open the gallery.");
}A small mistake, explained
What goes wrong
Using assignment inside a condition can change a variable rather than compare it.
How to fix it. Check the operator carefully. Use === for a strict equality check and test both branches.
Try it yourself
Run the example with 0, 1 and the string "0". Explain why the string takes a different branch.
Further reading
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Functions & return valuesTurn a small task into a named operation.