FAQ: Conditional Statements - The switch keyword

This community-built FAQ covers the “The switch keyword” exercise from the lesson “Conditional Statements”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The switch keyword

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

A post was split to a new topic: Why we have to use “break” after default

The last break; at the end of the whole block is necessary? If so, why? There’s no more cases incoming.

Thanks.

19 Likes

You are correct in that assessment. The author wrote it into the SCT so we have no choice but to humor them. Technically, there is no break in the default case since it is the last expression in the switch statement.

18 Likes

I guess, that was a joke :slight_smile: :

Remember to add the break keyword at the end of the default case.

But apart from that, there was a confusing line in the explanation part:

Without the break keyword at the end of each case, the program would execute the code for all matching cases and the default code as well.

Why matching? Wouldn’t it just run till the next break or to the end of the block, if no breaks are met on the way, no matter if case is matched or not?

2 Likes

When a case action does not include return, the switch is still being parsed for other possible matches. Even if none are found, the default case will execute, on top of whatever action was carried out on the first match. break directs control flow to the next statement AFTER the switch body.

Recall that case must match the given switch expression in order for control flow to enter that branch. Only in cases where we wish to include the default case in all instances would we omit the break on each case branch, which is highly unusual.

6 Likes

What are some real-life scenarios where one might want their program to execute multiple cases in one switch code block?

5 Likes

How would you make the test of each case case-insensitive? In other words, if I want both ‘first place’ and ‘First Place’ to return ‘You get the gold medal!’, what is the neatest way to code this?

switch (athleteFinalPosition.toLowerCase()) {

}

will transform the expression to lowercase so the cases can all be lowercase.

2 Likes

Two glaring errors in this one:

  1. The break keyword is not required in the default condition.

Without the break keyword at the end of each case, the program would execute the code for all matching cases and the default code as well.

  1. Also incorrect, it will execute for all cases, matching or not. You can even try it in the editor: remove the break keywords from all cases, you will notice it outputs to the console for ALL cases.
6 Likes

Good catch, @arc3849099512.

Can you elaborate more on the return function with example as u mentioned.

Thank u @mtf

Consider this function and switch…

function foo (bar) {
    switch (bar) {
    case 'faz': '';
    case 'baz': '';
    case 'foo': '';
    case 'bar': '';
    default: return false;
    }
    return true
}

What will the return be in the following four calls?

console.log(foo('faz'));
console.log(foo('baz'));
console.log(foo('foo'));
console.log(foo('bar'));

Answer? false, in all four log outs.

Yes, there are no actions in the case branches, but it is more the absence of ‘break’ that results in flow traveling all the way down to the default branch.

Now let’s set the case branches…

function foo (bar) {
    switch (bar) {
    case 'faz': break;
    case 'baz': break;
    case 'foo': break;
    case 'bar': break;
    default: return false;
    }
    return true
}

Now the four statements will all result in true being returned since break interrupts the switch and the line following it is executed (return true).

4 Likes

Thank you Mr. Roy. It helped in my clarification. :slight_smile:

1 Like

Hi!
I’d like to know whether it’s possible to use comparison operators within cases.

I wrote this to practice, and it works fine.

 let a = 11

 switch (a)
{
case 11: {console.log('eleven')};
  break;
case 12: {console.log('twelve')};
  break;
  
default: {console.log('other number')};
  break;
}

But then I thought, what if I want to check not a specific value, but any value that is higher than, e.g., 5? It looks like it’s not possible. Should I use if/else instead?

It is less common, but this works as expected:

switch (true) {
case a < 5: break;
case a === 5: break;
case a < 10: break;
case a === 10: break;
default: // a > 10
}

Codecademy says switch statements are a good alternative syntax to multiple else if statements, but now with ES6, can the ternary operator replace switch statements?

Ternary expressions are ES5, and unchanged in ES6. We could always nest ternaries but most teachers would discourage using them in complex situations.

 > randint = (h, k) => Math.floor(Math.random() * h) + k
<- (h, k) => Math.floor(Math.random() * h) + k
 > [a, b] = [randint(10, 1), randint(10, 1)]
<- (2) [5, 6]
 > console.log(a < b ? -1 : a > b ? 1 : 0)
   -1
<- undefined
 > 

We can create readable expressions, all the same, so long as we break them up…

 > double = x => 2 ** x
<- x => 2 ** x
 > halve = x => x / 2
<- x => x / 2
 > square = x => x ** 2
<- x => x ** 2
 > root = x => x ** 0.5
<- x => x ** 0.5
 > [a, b] = [randint(100, 1), randint(100, 1)]
<- (2) [92, 71]
 > console.log(
     a < b ? double(a) : 
     a > b ? halve(a) : 
     a % 2 ? square(a) :    // known state: a === b
     root(a)
   )
   46
<- undefined
 > 

Extra Study

Classes will come into play, albeit a little yet down the road. Bookmark this for when they do…

class RandomPair {
  randInt (h, k) { return Math.floor(Math.random() * h) + k }
  constructor() {
    [this.a, this.b] = [this.randInt(100,1), this.randInt(100,1)]
  }
}
 > new RandomPair
<- RandomPair {a: 88, b: 60}

Doesn’t matter, pick one that gets the job done and spend the brain cycles elsewhere.
Also, if some language feature doesn’t really add anything to your toolkit then you may as well pretend it doesn’t exist.