DEV Community

Cover image for JavaScript Basics: Ternary Operator, Truthy/Falsy, and Switch Case
Kathirvel S
Kathirvel S

Posted on

JavaScript Basics: Ternary Operator, Truthy/Falsy, and Switch Case

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;
Enter fullscreen mode Exit fullscreen mode

Example

let age = 20;

let message = age >= 18 ? "Adult" : "Minor";

console.log(message);
Enter fullscreen mode Exit fullscreen mode

Instead of:


if (age >= 18) {
  message = "Adult";
} else {
  message = "Minor";
}
Enter fullscreen mode Exit fullscreen mode

Use ternary for short and simple conditions only.

Truthy and Falsy in JavaScript:

  • In JavaScript, not everything is just true or false.
  • Some values are treated as false automatically.

Falsy Values

These are falsy:

false
0
""
null
undefined
NaN

Enter fullscreen mode Exit fullscreen mode

Truthy Examples


"hello"
1
[]
{}
"0"
"false"
Enter fullscreen mode Exit fullscreen mode

Even an empty array [] and empty object{} are truthy!

Example:

if (username) {
  console.log("User exists");
} else {
  console.log("No username");
}
Enter fullscreen mode Exit fullscreen mode

Since "" is falsy, it prints:

No username
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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)