Project : Eight Ball , require help with Swich statements

Hi switches are kinda new to me and while messing around i found some problems.
Could anyone explain me why case 0,1 run fine but the others do not.

//Generate and store the Eight Ball let randomNumber = Math.floor(Math.random() * 8); let eightBall = randomNumber; console.log(eightBall); switch (eightBall) { case 0: console.log(`It is certain`); break; case 1: console.log("It is decidedly so"); break; case eightBall == 2: console.log("Reply hazy try again"); break; case eightBall === 3: console.log("Cannot predict now"); /* case <= 10: console.log("this returns error"); */ case eightBall <= 10: //this does not return error console.log("this should always be run"); default: console.log("default case has been executed"); } console.log(randomNumber);

Thanks in advance for the help.

Hi there!

Welcome to the forums.

eightBall is the case you are switching. So you can read it like an if…else if…

switch (eightBall) {
  case 0: //if eightBall === 0
    execute this line
    break;
  case 1: //if eightBall === 1
    execute this line
    break;
  .
  .
  .
}

This is why only 0, 1, and default work. The other cases are invalid.

e.g.,
case eightBall === 2 and case eightBall === 3 is invalid because eightBall is inferred through the switch

case eightBall <= 10 is invalid because conditionals cannot be used in switch statements.

Thank you kira.
So if i understood right, the case (s) cannot contain Operators ?

let varA = 10; let varB = 5; switch (true) { case varA + varB == 15: //this returns an error console.log("case 0 has been run"); break; default: ceonsole.log("default code has been run"); break; }

case is a simple bool check, that evaluates the value of a switch (expression) matches the value of said case.

wait conditionals cannot be used in switch statements? then do we have to use normal if…else statements if we want to have conditional statements?

Seems you can, though im not sure. ( take a look at this version of the code they run fine)
Operators/Conditionals seem to work, the other day my trouble was probably due codecademy’s project interface locking things that should run fine.

let varA = 10; let varB = 5; switch (false) { /* case varA + varB == 10: //this seems to work outside Codecademy's project interface console.log("case 0 has been run"); break; */ case varB > varA: console.log("case 1 has been run"); break; default: console.log("default code has been run"); break; }

I just wanted to reply to clarify.

It’s not that you can’t use conditionals but you shouldn’t use conditionals in switch statements. It works (in some cases shown) because it is valid code, but it’s not standard and can overly complicate a string of code that is easier done through if...else...

This is easily considered an opinion, but why try to re-create the wheel when it already exists, yeah?

The jury is still out on that one. switch is ideal for when there are multiple (more than one or two) conditions. However it is the scenario that will dictate which model of code to use. If there is one should that applies it would be that we want our structure to be easy to read and maintain.

If we consider its use in the Magic 8-Ball scenario, it exceeds if..else if..else in that all possible cases are handled in a simple structure that JS can easily optimize for better performance. I know at this stage we need neither concern over performance nor over optimization, and focus only on writing code that works (for now). This construct looks after that for us, so it is moot.

The above is simply comparing values, and not conditionals. For my own part, I would use an object, not a switch when comparing only values and returning a fixed expression. There is little to no logic in such a case. But when there is logic contained in code blocks for each case, AND each case is a conditional, my first choice would be a switch, especially if there is no intention to port the code over to another language that may not support switch().

If one was to object, it would be to using, switch (false) { } instead of, switch (true) { }. We’re looking for truthiness (truth value), not falsiness. Again, in the case of one or two conditionals, switch is better set aside in favor of if..else.

We can also leverage the fall-through potential of a switch, in cases where more than one condition may apply (as opposed to using AND/OR logic). This is something to explore as opposed to shooing it aside as a taboo. We should always explore and push the limits to learn as much as we can about the inner workings, even if we set it aside, afterwards. Knowing a thing is better than choosing not to learn about it, if it is to become a useful tool in our kit. Just saying.

Segue to this topic, while we know it is solved, it suggests a need to explore further the ideas, namely the fall through. I don’t have a quick answer in this regard but wonder if ‘fizz buzz’ won’t help to demonstrate that concept. Let’s try it…

First, we will want to create a ‘range’ object of some variable length. The starting value will be zero.

const range = function (s) {
    s = new Array(s).fill(0);
    s.forEach(function (x, i) {
        this[i] += i;
    }, s)
    return s
}

x is unused, but we need it in the syntax to expose the index. this is the array we are iterating. Having the index makes it possible to mutate that array.

Thank you both for the different point of views,

It is true that through the project, one can forget that a switch can run multiple conditions before a break, very clever, would not have thought to replace say a long conditonal statement (ANDs) with a easier to read switch, i wonder which would be more efficient script wise.

As for the Array one, i might be getting too ahead :joy: i’ll come to this one in a week or so

1 Like

It’s just the start, and a segue at that. Not even sure the example I have in mind will work. It’s to demonstrate ‘fall through’, though I may be on the wrong path in my own mind. We’ll have to see. The carry away is the above snippet that gives a range starting with zero of any prescribed length. That has to be worth something. I need it in my demo, so for sure it has a use.

My fizz buzz will follow, let’s hope it demonstrates the behavior of ‘fall through’ or I’ll surely look dodgy.