Chapter 3 of 34
~11 minOperators & Control Flow
Operators let you compute and compare values, and control flow statements let your program make decisions. Together they are how you express logic in code.
Arithmetic, Comparison, and Logical Operators
Arithmetic operators (`+ - * / % **`) do math. Comparison operators (`< > <= >= == === != !==`) compare values and return a boolean. Logical operators (`&& || !`) combine boolean expressions.
`&&` and `||` are also used for "short-circuiting" - `a && b` returns `b` only if `a` is truthy, and `a || b` returns `a` if it is truthy, otherwise `b`. This is a common pattern for default values and conditional calls.
Try it yourself
Comparison and logical operators<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
The Ternary Operator
The ternary operator `condition ? valueIfTrue : valueIfFalse` is a compact way to write a simple if/else that produces a value, often used for inline decisions in JSX or template strings.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
if/else and switch
`if`/`else if`/`else` chains run one branch based on boolean conditions. A `switch` statement compares one value against several possible cases, and is often clearer when you have many discrete options for the same variable. Remember `break` - without it, execution "falls through" into the next case.
Try it yourself
switch with fallthrough avoided by break<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Truthy and Falsy Values
When a value is used where a boolean is expected (like an `if` condition), JavaScript converts it. Only `false`, `0`, `-0`, `""`, `null`, `undefined`, and `NaN` are falsy. Everything else - including `"0"`, `[]`, and `{}` - is truthy.
Coding challenge
Write a function-free script: declare a score number variable, then use if/else to log "Pass" if score is 60 or above, otherwise log "Fail". Test it with a score of 75.
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. What does `'' || 'Guest'` evaluate to?
2. Which of these values is falsy?
3. What keyword prevents a switch statement from falling through to the next case?
4. What does the ternary operator `a ? b : c` do?