JavaScript - Conditional Operators

Hello there, future JavaScript wizards! Today, we're going to dive into the magical world of conditional operators. Don't worry if you've never written a line of code before – I'll be your friendly guide on this exciting journey. So, grab your virtual wands (keyboards), and let's cast some conditional spells!

JavaScript - Conditional Operators

What Are Conditional Operators?

Imagine you're a traffic light. Your job is to decide whether cars should go or stop. That's exactly what conditional operators do in JavaScript – they help our programs make decisions based on certain conditions.

The Ternary Operator: The Swiss Army Knife of Conditionals

The star of our show today is the ternary operator. It's like a compact, super-efficient if-else statement. Let's break it down:

condition ? expressionIfTrue : expressionIfFalse

It's as if we're asking a question:

  • If the answer is yes (true), do the first thing.
  • If the answer is no (false), do the second thing.

Syntax: The Recipe for Conditional Magic

Let's look at the ingredients of our conditional potion:

  1. condition: This is our question. Is it raining? Is the user logged in? Is the number even?
  2. ?: This is like saying "then..."
  3. expressionIfTrue: What to do if the condition is true
  4. :: This is like saying "otherwise..."
  5. expressionIfFalse: What to do if the condition is false

Example 1: The Weather Decider

Let's start with a simple example. We'll create a program that decides whether to bring an umbrella based on the weather.

let isRaining = true;
let decision = isRaining ? "Bring an umbrella" : "Leave the umbrella at home";
console.log(decision);

If you run this code, it will output: "Bring an umbrella"

Let's break it down:

  • isRaining is our condition. It's set to true.
  • If it's raining (isRaining is true), our expression returns "Bring an umbrella".
  • If it's not raining, it would return "Leave the umbrella at home".
  • We store this result in the decision variable.

Try changing isRaining to false and see what happens!

Example 2: The Age Checker

Now, let's create a program that checks if someone is old enough to vote.

let age = 20;
let canVote = age >= 18 ? "Yes, you can vote!" : "Sorry, you're too young to vote.";
console.log(canVote);

This will output: "Yes, you can vote!"

Here's what's happening:

  • We set the age to 20.
  • Our condition is age >= 18 (is age greater than or equal to 18?).
  • If true, we return "Yes, you can vote!".
  • If false, we return "Sorry, you're too young to vote."

Try changing the age to 16 and see how the output changes!

Example 3: The Grade Assigner

Let's get a bit more complex. We'll create a program that assigns a grade based on a score.

let score = 85;
let grade = score >= 90 ? 'A' :
            score >= 80 ? 'B' :
            score >= 70 ? 'C' :
            score >= 60 ? 'D' : 'F';
console.log(`Your grade is: ${grade}`);

This will output: "Your grade is: B"

Wow, that looks different! We've actually chained multiple ternary operators together. It's like a waterfall of decisions:

  • First, we check if the score is 90 or above. If yes, it's an 'A'.
  • If not, we check if it's 80 or above. If yes, it's a 'B'.
  • This continues down to 'F' for anything below 60.

It's a powerful technique, but use it wisely – too many chains can make your code hard to read!

Handling null values: The Null Coalescing Operator

Sometimes, we need to deal with values that might be null or undefined. Enter the null coalescing operator: ??

let username = null;
let displayName = username ?? "Guest";
console.log(`Welcome, ${displayName}!`);

This will output: "Welcome, Guest!"

Here's what's happening:

  • If username is null or undefined, we use "Guest" instead.
  • If username has a value, we use that.

It's a handy way to provide default values!

The Conditional Operator Cheat Sheet

Here's a quick reference table of the operators we've learned:

Operator Name Purpose
?: Ternary Operator Make a decision between two values based on a condition
?? Null Coalescing Operator Provide a default value when dealing with null or undefined

Remember, practice makes perfect! Try creating your own examples and experiments with these operators. Before you know it, you'll be conducting a whole orchestra of conditionals in your code!

Happy coding, and may your conditionals always be true (when you want them to be)!

Credits: Image by storyset