If you're learning JavaScript, understanding conditionals is very important. In this post, we’ll quickly cover:
- Ternary Operator
- Truthy & Falsy Values
- Switch Case
Let’s keep it simple
Ternary Operator (Short If-Else)
The ternary operator is a short way to write an if...else.
Syntax
condition ? valueIfTrue : valueIfFalse;
Example
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message);
Instead of:
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
Use ternary for short and simple conditions only.
Truthy and Falsy in JavaScript:
- In JavaScript, not everything is just
trueorfalse. - Some values are treated as false automatically.
Falsy Values
These are falsy:
false
0
""
null
undefined
NaN
Truthy Examples
"hello"
1
[]
{}
"0"
"false"
Even an empty array [] and empty object{} are truthy!
Example:
if (username) {
console.log("User exists");
} else {
console.log("No username");
}
Since "" is falsy, it prints:
No username
Remember: 0 is also falsy!
Switch Case in Javascript:
switch is useful when checking one variable against many values.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("Almost weekend");
break;
default:
console.log("Regular day");
}
Always use break, or the code will continue to the next case.
Quick Summary
- Ternary = short if...else
- Falsy values: false, 0, "", null, undefined, NaN
- Switch is great for multiple fixed values
- Don’t forget break in switch
Top comments (0)