Skip to main content

Command Palette

Search for a command to run...

JavaScript Ternary 🎯 and Switch 🔄: Simplify Your Decisions

Published
•3 min read•View as Markdown
JavaScript Ternary 🎯 and Switch 🔄: Simplify Your Decisions

JavaScript TERNARY OPERATOR 🚀

1. Quick Overview 🏎️

The ternary operator is JavaScript’s shortcut for if-else. It’s all about making quick decisions with just one line!

condition ? codeIfTrue : codeIfFalse;

2. Basic Usage: Morning or Afternoon? 🌞🌙

Let’s greet someone based on the time ⏰.

let time = 9;
let greeting = time < 12 ? "Good morning!" : "Good afternoon!";
console.log(greeting); // Output: "Good morning!"
  • What's happening?
    If time < 12 is true, it says "Good morning!" Otherwise, "Good afternoon!" Nice and clean, right?

3. Boolean Power 💪

Simplify your logic with booleans. One true or false can drive the whole operation.

let isStudent = false;
let message = isStudent ? "You are a student" : "You are NOT a student";
console.log(message); // Output: "You are NOT a student"
  • What's happening?
    If isStudent is true, you'll see "You are a student". If not, "You are NOT a student". Easy peasy!

4. Calculate On The Fly 🧮

Ternary isn’t just for messages. It’s awesome for calculations too!

let purchaseAmount = 99;
let discount = purchaseAmount >= 100 ? 10 : 0;
console.log(`Your total is $${purchaseAmount - purchaseAmount * (discount/100)}`);
// Output: "Your total is $99"
  • What's happening?
    No discount if the amount is below $100. Keep that wallet safe!

5. Everyday Practical Example 🛒

It’s time to shop! Here’s how you calculate discounts without breaking a sweat.

let purchaseAmount = 125;
let discount = purchaseAmount >= 100 ? 10 : 0;
console.log(`Your total is $${purchaseAmount - purchaseAmount * (discount/100)}`);
// Output: "Your total is $112.50"
  • What's happening?
    When the total is more than $100, you get a 10% discount. Keep your cash in check!

JavaScript SWITCHES! 💡

1. Quick Overview 🔄

The switch statement is perfect for situations where you have multiple conditions to check. It's like an efficient upgrade from writing several if-else statements.

switch (variable) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // code block
}

2. Basic Example: What Day Is It? 🗓️

Let’s figure out what day of the week it is based on a number!

const day = 7;

switch (day) {
  case 1:
    console.log("It is Monday");
    break;
  case 2:
    console.log("It is Tuesday");
    break;
  case 7:
    console.log("It is Sunday");
    break;
  default:
    console.log(`${day} is not a valid day`);
}
// Output: "It is Sunday"
  • What's happening?
    The day variable is matched to each case, and when it finds the match (case 7), it outputs "It is Sunday". 🎉

3. Don’t Forget the Break 🛑

The break statement is crucial. Without it, fall-through happens and all subsequent cases will run!

const day = 2;

switch (day) {
  case 1:
    console.log("It is Monday");
    break;
  case 2:
    console.log("It is Tuesday");
    // break missing here!
  case 3:
    console.log("It is Wednesday");
    break;
  default:
    console.log(`${day} is not a valid day`);
}
// Output: "It is Tuesday"
//         "It is Wednesday"
  • What's happening?
    Since there’s no break after case 2, it keeps running into case 3! Be careful!

4. Advanced Example: Grading System 📊

Switch isn’t just for exact matches; you can get fancy with conditions too!

const testScore = 92;
let letterGrade;

switch (true) {
  case testScore >= 90:
    letterGrade = 'A';
    break;
  case testScore >= 80:
    letterGrade = 'B';
    break;
  case testScore >= 70:
    letterGrade = 'C';
    break;
  case testScore >= 60:
    letterGrade = 'D';
    break;
  default:
    letterGrade = 'F';
}

console.log(`Letter grade: ${letterGrade}`);
// Output: "Letter grade: A"
  • What's happening?
    By switching on true, we’re able to evaluate each condition, assigning a letter grade based on the test score. Pretty cool, right?

5. Use Cases for Switch 🛠️

Switch statements shine when you have lots of possible cases (like menu selections, error codes, etc.). It makes your code cleaner and easier to manage.