Getting Started> Control Flow> Ternary Operator: switch statement question?


#1
let favoritePhrase = 'Love That!';

favoritePhrase === "Love That!" ?
   console.log ("I love that!"):
   console.log ("I don't love that!");

I was working on this bit of code from Lesson 10 in Control Flow. Maybe we learn this later, but I was wondering how to use a Ternary Operator with a switch statement? Because the code above seems like it works only because ES6 knows that the second option has to be the ‘else’ statement, correct? Or is it that it runs the first option because it’s truthy and the second if it’s falsy? But if I had multiple conditions how would a switch statement be used with a Ternary Operator?
Say I wanted to use a previous example from Lesson 7 with the full moon and the werewolf? I have multiple potential logs.

let moonPhase = "full";
switch (moonPhase) {
  case "full":
    console.log("Howl!");
    break;
  case "mostly full":
    console.log("Arms and legs are getting hairier");
    break;
  case "mostly new":
    console.log("Back on two feet");
    break;
  default:
    console.log("Invalid moon phase");
    break;
}

How would the syntax work? This is my best guess on how to get it to log in the console:

let moonPhase = "full";
switch moonPhase ?
  case "full":
    console.log("Howl!");
    break;
  case "mostly full":
    console.log("Arms and legs are getting hairier");
    break;
  case "mostly new":
    console.log("Back on two feet");
    break;
  default:
    console.log("Invalid moon phase");
    break;

Any help is appreciated.


#2

ternary operator doesn’t exist for switch statement


#3

okay, so does it look at the first block of code as the first log running if truthy, and the second if it’s falsy? Or is it the first one is an if, and the last one is an else? Or I guess those are pretty much the same thing


#4

switch statement is just a nicer way of writing if, lot of else if and else statement.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.