Lesson guide
Learning objectives
- Explain the main purpose of Conditional branching: if, '?' in JavaScript.
- Identify the syntax, APIs, or concepts introduced in this lesson.
- Use the examples to predict how JavaScript will behave before you run similar code.
- Connect this topic to nearby lessons in JavaScript Fundamentals.
Real-world context
This lesson matters when you need to recognize where Conditional branching: if, '?' fits into real JavaScript programs. Sometimes, we need to perform different actions based on different conditions.
Key ideas
- Conditional branching: if, '?' is part of the JavaScript Fundamentals chapter, so it builds on the surrounding concepts rather than standing alone.
- Read each code example in two passes: first for the result, then for the rule that explains the result.
- When a section compares similar features, focus on the condition that makes you choose one feature over another.
Key terms
- Conditional branching: if, '?'
- Conditional
- branching
- JavaScript Fundamentals
- JavaScript
Sometimes, we need to perform different actions based on different conditions.
To do that, we can use the if statement and the conditional operator ?, that’s also called a “question mark” operator.
The “if” statement
The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a block of code.
For example:
let year = prompt('In which year was ECMAScript-2015 specification published?', ''); if (year == 2015) alert( 'You are right!' );
In the example above, the condition is a simple equality check (year == 2015), but it can be much more complex.
If we want to execute more than one statement, we have to wrap our code block inside curly braces:
if (year == 2015) { alert( "That's correct!" ); alert( "You're so smart!" ); }
We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.
Boolean conversion
The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean.
Let’s recall the conversion rules from the chapter Type Conversions:
- A number
0, an empty string"",null,undefined, andNaNall becomefalse. Because of that they are called “falsy” values. - Other values become
true, so they are called “truthy”.
So, the code under this condition would never execute:
if (0) { // 0 is falsy ... }
…and inside this condition – it always will:
if (1) { // 1 is truthy ... }
We can also pass a pre-evaluated boolean value to if, like this:
let cond = (year == 2015); // equality evaluates to true or false if (cond) { ... }
The “else” clause
The if statement may contain an optional else block. It executes when the condition is falsy.
For example:
let year = prompt('In which year was the ECMAScript-2015 specification published?', ''); if (year == 2015) { alert( 'You guessed it right!' ); } else { alert( 'How can you be so wrong?' ); // any value except 2015 }
Several conditions: “else if”
Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.
For example:
let year = prompt('In which year was the ECMAScript-2015 specification published?', ''); if (year < 2015) { alert( 'Too early...' ); } else if (year > 2015) { alert( 'Too late' ); } else { alert( 'Exactly!' ); }
In the code above, JavaScript first checks year < 2015. If that is falsy, it goes to the next condition year > 2015. If that is also falsy, it shows the last alert.
There can be more else if blocks. The final else is optional.
Conditional operator ‘?’
Sometimes, we need to assign a variable depending on a condition.
For instance:
let accessAllowed; let age = prompt('How old are you?', ''); if (age > 18) { accessAllowed = true; } else { accessAllowed = false; } alert(accessAllowed);
The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.
The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.
The syntax is:
let result = condition ? value1 : value2;
The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.
For example:
let accessAllowed = (age > 18) ? true : false;
Technically, we can omit the parentheses around age > 18. The question mark operator has a low precedence, so it executes after the comparison >.
This example will do the same thing as the previous one:
// the comparison operator "age > 18" executes first anyway // (no need to wrap it into parentheses) let accessAllowed = age > 18 ? true : false;
But parentheses make the code more readable, so we recommend using them.
Please note:
In the example above, you can avoid using the question mark operator because the comparison itself returns true/false:
// the same let accessAllowed = age > 18;
Multiple ‘?’
A sequence of question mark operators ? can return a value that depends on more than one condition.
For instance:
let age = prompt('age?', 18); let message = (age < 3) ? 'Hi, baby!' : (age < 18) ? 'Hello!' : (age < 100) ? 'Greetings!' : 'What an unusual age!'; alert( message );
It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an ordinary sequence of tests:
- The first question mark checks whether
age < 3. - If true – it returns
'Hi, baby!'. Otherwise, it continues to the expression after the colon “:”, checkingage < 18. - If that’s true – it returns
'Hello!'. Otherwise, it continues to the expression after the next colon “:”, checkingage < 100. - If that’s true – it returns
'Greetings!'. Otherwise, it continues to the expression after the last colon “:”, returning'What an unusual age!'.
Here’s how this looks using if..else:
if (age < 3) { message = 'Hi, baby!'; } else if (age < 18) { message = 'Hello!'; } else if (age < 100) { message = 'Greetings!'; } else { message = 'What an unusual age!'; }
Non-traditional use of ‘?’
Sometimes the question mark ? is used as a replacement for if:
let company = prompt('Which company created JavaScript?', ''); (company == 'Netscape') ? alert('Right!') : alert('Wrong.');
Depending on the condition company == 'Netscape', either the first or the second expression after the ? gets executed and shows an alert.
We don’t assign a result to a variable here. Instead, we execute different code depending on the condition.
It’s not recommended to use the question mark operator in this way.
The notation is shorter than the equivalent if statement, which appeals to some programmers. But it is less readable.
Here is the same code using if for comparison:
let company = prompt('Which company created JavaScript?', ''); if (company == 'Netscape') { alert('Right!'); } else { alert('Wrong.'); }
Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.
The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that. Use if when you need to execute different branches of code.
Common mistakes
- Skipping the small examples and then missing the exact rule that Conditional branching: if, '?' depends on.
- Copying code without changing one value at a time to see which part controls the result.
- Treating similar-looking syntax or APIs as interchangeable before checking their edge cases.
Summary
- Conditional branching: if, '?' gives you one more piece of the JavaScript mental model.
- The examples in this lesson are the quickest way to check whether the rule is clear.
- Revisit the key terms when you meet the same idea in later chapters.
Predict
Before running this check, predict the three labels. Trace the if / else if / else chain first, then compare it with the conditional operator used for access.
Reveal explanation
The output is Hi, baby! blocked, then Greetings! allowed, then What an unusual age! allowed. The if chain stops at the first truthy condition: 2 < 3 chooses the baby greeting, 18 < 18 is false but 18 < 100 is true, and 120 reaches the final else. The conditional operator age >= 18 ? "allowed" : "blocked" returns one value, so it is a good fit for the access label rather than for executing whole branches of code.
Try it
Change the second call to describeAge(17) and add describeAge(100). Predict both labels before running, especially the boundary where < 100 stops being true.
Practice
- Rewrite one example from this lesson without looking at the original, then run it and compare the result.
- Change one input, operator, method call, or option in a code sample and predict what will happen before running it.
- Explain Conditional branching: if, '?' in your own words as if you were reviewing it with another learner.
Keep learning
Continue with Logical operators when you are ready for the next lesson.