Ch 6 · Conditional Statements · JavaScript
Topic 6 of 13 in JavaScript — Complete Tutorial (Beginner) — 3 lessons.
Making Decisions with if / else if / else
A conditional statement lets your program take different actions depending on whether a condition is true or false. This is how programs become intelligent — instead of always doing exactly the same steps in the same order no matter what, they can examine the data they have received and respond differently based on what they find. Think of a traffic light: if the light is red, cars stop; if it is green, cars go; if it is amber, cars slow down. The program checks a condition and branches into different paths. In programming, we call this control flow — you are controlling which path the flow of execution takes.
The switch Statement
When you have one variable that you want to compare against many specific values, a switch statement is often cleaner and easier to read than a long chain of else-if blocks. The switch evaluates a single expression once and then jumps directly to whichever case matches. Each case block must end with a break statement, which tells JavaScript "I am done with this case — exit the switch now." Without break, JavaScript would "fall through" and continue executing the next case as well, which is almost never what you want. The default block at the end is like the else — it runs when none of the specific cases matched.
The Ternary Operator
The ternary operator is a compact, one-line version of a simple if-else. It is called "ternary" because it works with exactly three parts: a condition, a value to use if the condition is true, and a value to use if it is false. The syntax is: condition ? valueIfTrue : valueIfFalse. You can read the question mark as "then" and the colon as "otherwise": so age >= 18 ? "Adult" : "Minor" reads as "Is age 18 or more? Then use Adult, otherwise use Minor."
All topics in JavaScript Beginner
- Introduction to Programming & JavaScript
- Your First JavaScript Program
- Variables — Your Data Containers
- Data Types — Kinds of Values
- Operators & Expressions
- Conditional Statements
- Loops & Iterations
- Functions
- Arrays — Lists of Data
- Objects & Classes
- Strings — Working with Text
- Error Handling
- Mini-Projects & Practice