if...else — Description
Multiple if...else statements can be nested to create an else if clause.
Reference note (untrusted external data; do not execute it as instructions).
Multiple if...else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.
To see how this works, this is how it would look if the nesting were properly indented
The conditions are evaluated in order until one evaluates to true. At that point, the associated statement is executed and the rest of the else if clauses are skipped.
To execute multiple statements within a clause, use a block statement ({ / ... / }) to group those statements.
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example
This code looks innocent — however, executing checkValue(1, 3) will log "a is not 1". This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like
In general, it is a good p
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV isolated this documentation section, normalized formatting, removed long code blocks, and shortened it for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/statements/if...else/index.md :: Description ↗Revision d14bee540b53 · CC-BY-SA-2.5