Switch and expression

Hello there !
I started recently the Java course and was wondering if you could use the switch with multiple expressions (I don’t know if the code i tried didn’t work cause of a mistake or juste because it can’t be done)

I tried this :
switch (actualSleepHours,idealSleepHours) {
case actualSleepHours === idealSleepHours:
return ‘You got the perfect amount of sleep’;
break;
case actualSleepHours < idealSleepHours:
return ‘You need more rest mate’;
break;
case actualSleepHours > idealSleepHours:
return ‘Ya sleepin too much pal’;
break;
}

(It’s in a function in this project : https://www.codecademy.com/courses/introduction-to-javascript/projects/sleep-debt-calculator)

Thanks in advance !

Are you getting an error from this…

switch (actualSleepHours,idealSleepHours) {

?

In JS that might not raise an error. but the switch may not work…

 > a = 7
<- 7
 > b = 8
<- 8
 > switch(a, b) {
       case a > b: console.log('too much'); break;
       case a < b: console.log('not enough'); break;
       case a === b: console.log('just right')
  }
<- undefined
 > 

No error is raised, but the cases are not evaluated, as we can see by the response.

 > a = 7
<- 7
 > b = 8
<- 8
 > switch(true) {
       case a > b: console.log('too much'); break;
       case a < b: console.log('not enough'); break;
       case a === b: console.log('just right')
   }
   not enough
<- undefined
 > 

Note that if this was in a function and we used return, there would be no need for break. That keyword can be removed from all your cases.

1 Like

thanks for the break tips, didn’t notice that, as my level is still quite low in programming for now :slight_smile:

I’m not used with the syntax you used, but if i understood corectly, in the first case, the switch doesn’t work with 2 expressions is that right ?
For the second one i’m not sure that i’ve got it right, is the value still undefined or do we get the expected answer ?

Edit : so i ended the project with the if, and came back to it with the switch to check for the error. Odly, i’ve get an error message from the line “you need more rest mate”
return 'You need more rest mate;
^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Invalid or unexpected token

Edit 2 : Nvm, it came from a other line of code from the bottom, function switch work great with the syntax switch(true) that you gave me in the first message, thanks !

1 Like

Correct on the first one. JavaScript did not apply the arguments in the switch.

For the second one, we did get an response. The undefined can be ignored as it is the normal response of the console.

JS script is very similar to Java so makes for a simple comparison example. The two languages are not connected, though. Just similar.

A switch takes an expression as an argument and then matches it to the case expressions. If we look closely we see that the cases are boolean. The first one to match the argument will be the branch followed.

1 Like

I’d guess you solved this by adding a closing quote (before the semi-colon)?

Had created a whole new function to check for the error message, but copy/pasted it from the forum so the syntax was twisted a bit and then created the errors.
Then i started to work on the original function instead of the new one and forgot to delete the latest, so the bug was fixed, but i forgot to delete the lame copy/pasta :sweat_smile:

Anyway, switch(true) works fine apparently as long as the variables that it use are defined beforehand. Thanks for the help Mtf !

1 Like

That is well defined behaviour. The result of comma-separated expressions is the result of the last expression.

edit: throwing in some haskell because why not:

if | a > b     -> "too much"
   | a < b     -> "not enough"
   | otherwise -> "just right"

Or as a complete function:

sleepJudge slept ideal | slept > ideal = "too much"
                       | slept < ideal = "not enough"
                       | otherwise     = "just right"

The “switch” is part of the function itself, it’s not something separate…

1 Like

Yeah, I left off a default case which may well have been the branch followed had it been there. My Chrome browser is behaving wonky, of late, so I shut it down. That’s my console of choice when I don’t have a repl window open. Will have to complete the test with a default case and see what happens.

A long time ago someone wrote a really good article about switch in which they covered all the finer details. Wish I could find it again. Personally, I’ve never comma separated expressions in the argument so can only say this is the first I’m seeing it. Java being so similar to JS in this respect, I went on the assumption the behavior is similar.

switch (expression) {
case expr_1: ...
case expr_2: ...
default: ...
}

That solved it for the OP, which is fair enough. Love your Haskell example. Is it actually called a switch, or a multi-way conditional branch?


Newest test result

 > switch(a, b) {
       case a > b: console.log('too much'); break;
       case a < b: console.log('not enough'); break;
       case a === b: console.log('just right'); break;
       default: console.log(a, b)
   }
   7 8
<- undefined

So the switch did work, just none of the expressions matched. Going for one more test…

 > switch(a, b) {
       case a > b: console.log('too much'); break;
       case a < b: console.log('not enough'); break;
       case a === b: console.log('just right'); break;
       case 7: console.log('slept: ', a)
       case 8: console.log('ideal: ', b)
       default: console.log(a, b)
   }
   ideal:  8
<- undefined

which would agree entirely with what you suggested, @ionatan. Great point.

The only test you really need is:

console.log((3, 4))  // 4

It’s an expression, which is as far as a switch cares


Haskell doesn’t have anything called switch no, and it also has no statements, everything is an expression or a declaration. Haskell doesn’t specify what order things are executed so it fundamentally cannot have switches because that’s something that a switch does.

As an example, you could write down a series of instructions in English for how to solve some bit of math, and that would be how python/c/cpp/java/js/whatever works. Or you could write a math expression for it which doesn’t specify how it is to be evaluated but still has rules for how to do it, and that’s how haskell works.

imperative languages:
push 5
push 3
add

^this code says 5 has to be started with

functional:
5 + 3

…to some extent imperative languages can still re-order things if it can prove that it won’t affect the outcome. This gets difficult really quick because code can have side-effects anywhere in it
for haskell there’s no order to begin with, reordering is always something valid for the language to do, and furthermore the full expression doesn’t need to be evaluated if the result has been already found, while in imperative languages it’s difficult to prove that something is dead code so it has to be executed anyway. Theoretically you could evaluate different parts of an expression in parallel, while imperative code is by its nature a single thread, same thing here, it’s difficult to prove that it can be split.

1 Like