Conditionals (if/else/switch)
Learn to make decisions in JavaScript! Master if/else statements, switch cases, and conditional logic.
Learn to make decisions in JavaScript! Master if/else statements, switch cases, and conditional logic. This hands-on tutorial focuses on practical implementation of conditionals (if/else/switch) concepts.
Conditionals
Conditionals allow your code to make decisions. Without them, code would just run from top to bottom. With them, your program becomes intelligent!
1. The if Statement ๐ค
What is it?
The most basic form of decision making. It executes a block of code only if a specified condition is true.
How it works:
if (condition) { // do something }
2. The switch Statement ๐
What is it? A cleaner way to compare a single value against multiple options.
Why use it?
When you have many else if checks on the same variable, switch is more readable.
Crucial: Don't forget the break keyword! Without it, code "falls through" to the next case.
3. Truthy and Falsy Values ๐ญ
In JavaScript, values aren't just true or false. Every value can be treated as true or false in a conditional.
Falsy Values (Evaluate to false):
false0(and-0,0n)""(Empty string)nullundefinedNaN
Truthy Values (Evaluate to true):
- Everything else!
"0"(String containing zero)"false"(String containing "false")[](Empty array){}(Empty object)
4. Ternary Operator โ
What is it?
A shorthand for if...else that fits on one line.
Syntax: condition ? valueIfTrue : valueIfFalse
Best Practice: Use it for simple assignments. Avoid nesting them (it gets hard to read).
5. Logical Operators in Conditionals ๐ง
You can combine conditions using && (AND), || (OR), and ! (NOT).
Practical Example: Access Control System ๐
AI Mentor
Confused about "JavaScript conditionals, if/else, switch, truthy/falsy values, and ternary operator"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4Which of these is a 'falsy' value?
Key Takeaways
โ
if/else is for general logic.
โ
switch is for checking one variable against many values.
โ
Truthy/Falsy: Learn the 6 falsy values (false, 0, "", null, undefined, NaN).
โ
Ternary (? :) is great for simple assignments.
โ
Short-circuiting (&&, ||) is a powerful pattern.
What's Next?
Now that you can make decisions, let's learn how to repeat actions with Loops!
Keep coding! ๐