FAQ: Conditional Statements - The switch keyword

Are you sure one needs to add break after a default case? :thinking:

Not in JavaScript, though in some other languages like C it is required.

1 Like

I can’t understand the difference between “Switch” and “if-else”.
as the lecture says

but imagine if we needed to check 100 different values! Having to write that many else if statements sounds like a pain!

same concept can be applied to “Switch” also. if we have 100 cases so we need to write 100 cases what’s the difference between them?

Their justification for using switch over if-else is slightly less redundant code and structure. It might also be easier to read.

There are two schools of thought concerning switch, one which favors it over if-else, the other that believes it to be syntactic sugar. Me, I’m not on either side. Simple, basic code is always the best place to start. Once it works then we can look for ways to smooth out the rough edges and look for redundancies and ways to simplify and/or improve.

Once you graduate to objects and have a handle on how they work, see if you can find a way to use one to take the place of switch.

1 Like

let groceryItem = ‘papaya’;

switch (groceryItem) {
case ‘tomato’:
console.log(‘Tomatoes are $0.49’);
break;
case ‘lime’:
console.log(‘Limes are $1.49’);
break;
case ‘papaya’:
console.log(‘Papayas are $1.29’);
break;
default:
console.log(‘Invalid item’);
break;
}

// Prints ‘Papayas are $1.29’

So whats happening here is when we make a switch statement we are checking different cases and using the break to terminate the switch statement
for each console.log output ending with the output ‘Papayas are 1.29’ which is the value that was assign to the variable groceryItem.

let me know if im understanding correctly.

I use else if and looks ok to me but I encounter the issue when I use ‘switch’. Can anyone help?

Below are both codes using ‘if…else if’ and using ‘switch’

the codes when use ‘if… else if’:

let wkgroceryBudget = 201;

if (wkgroceryBudget < 200) {console.log(‘We did a good job this week’);}

else if (wkgroceryBudget > 200) {console.log (‘Cut off a few from the list’);}

else {console.log(‘We reached ceiling.’);}

//weekly grocery bill warning me go over the budget with $201 (this one works)

The codes when I use switch for similar scenario (not works :frowning:

let monthBudget = 1005;

switch (monthBudget)

{case monthBudget < 1000: coonsole.log (‘Good job on saving’);

break;

case monthBudget > 1000: console.log(‘We need to save money next month.’);

break;

default: console.log(‘Remember, our monthly budget is only $1,000.’);

break;

}

//monthly budget warning (this one does not work only goes to default-

//regardless of different monthBudget vaules)

What data type does that expression yield?

A Boolean. Is your switch expression a Boolean?

The two must have the same data type else how can they match?

At the beginning, no matter what value I input <1000 or > 1000, the outcome is aways presented as default statement ‘Remember, our monthly budget is only $1,000.’

I then adopt your suggested boolean concept with one of previous examples you presented (#15/108) and it works now with either <1000 or >1000. This gives me the expected output statements. Can you tell me what boolean do here in switch statement (the logic behind switch(true)?

Separately, I also try with switch(false) statement, the output totally goes opposite. Why?

Below is revised codes that gives me expected output:

let monthBudget = 1000.5;

switch (true)

{

case monthBudget < 1000: console.log(‘Good job on saving.’);

break;

case monthBudget >1000: console.log(‘We need to save money next month.’);

break;

default: console.log(‘Remember, our monthly budget is only $1,000.’);

break;

}

Recall above we mention that the switch expression must match the data type of all the case expressions. Since your cases are boolean, then the switch must also be boolean. How many values are there in the boolean data type? Trick question, there are only two. true and false.

Given that all your case expressions are different, only one of them will be true (or none, hence ‘default’).

switch (true) {
    case x < 1000: // code; 
        break;
    case x > 1000: // code; 
        break;
    default: x === 1000;
}

While we would never write like this, it follows that if only one case is true, the rest are false so the first one encountered will be the branch followed.

Bottom line, if the switch expression is a number, then the case expressions must also be a number value; if it is a string, the cases must be string value. We are looking for an exact match (similar to a === b).

Anyone else confused by this? They make it seem as though the switch/case is a faster way to write else/if. But surely if you have 100 different values, you still have to write the 100 different values, or am I missing something?
I feel as if the else/if is easier to read and write, and now I’m having to learn two things that do the same?

Please how do I get the return value from a switch statement?

There is no ‘return value’, per se, as it is not a function object. It is a control flow construct.

Let’s say we have this inside a function:

const foo = function (bar) {
    let baz;
    switch (bar) {
    case 1: baz = bar
    case 2: baz = bar ** 2
    case 3: baz = bar * 3
    default: baz = bar * 2
    }
    return baz
}

In the above we declare a local variable, but do not define it. It gets its definition from the relevant case that the parameter matches, or if it does not match any case, is given a default value. When the switch has completed execution, we then return baz to whatever made the call to our function (the caller).

Don’t expect the arithmetic above to have any meaning beyond demonstration.

console.log(foo(1));    //  1
console.log(foo(2));    //  4
console.log(foo(3));    //  9
console.log(foo(4));    //  8
1 Like

Thank you sir @mtf for the reply

1 Like

switch and case statements are a way to write conditional statements in a more concise and sometimes more readable manner than a long series of if and else if statements. The primary use case for switch is when you have a variable that can take on different values and you want to execute different code blocks based on those values.

Here’s an example in JavaScript:

let fruit = 'apple';

switch (fruit) {
  case 'apple':
    console.log('It\'s an apple.');
    break;
  case 'banana':
    console.log('It\'s a banana.');
    break;
  case 'orange':
    console.log('It\'s an orange.');
    break;
  default:
    console.log('Unknown fruit.');
}

which can be written as … in if... else statements:

let fruit = 'apple';

if (fruit === 'apple') {
  console.log('It\'s an apple.');
} else if (fruit === 'banana') {
  console.log('It\'s a banana.');
} else if (fruit === 'orange') {
  console.log('It\'s an orange.');
} else {
  console.log('Unknown fruit.');
}

In this simple example, the switch statement might not seem much shorter or clearer, but as the number of cases increases, the switch statement can become more concise and readable.

The key difference is that the switch statement evaluates the expression (fruit in this case) once and then compares the result to different cases. In contrast, the if and else if statements evaluate each condition sequentially until one is true.

I’m just learning and trying to figure this out and i know it’s an example but it just seems like this would be horribly slow if it was an actual list. wouldn’t you be able to write this like this as well?

let groceryPrices = { tomato: 0.49, papaya: 1.29, apple: 0.99, banana: 0.39, // ... more items }; let groceryItem = 'papaya'; let message = groceryPrices.hasOwnProperty(groceryItem) ? `${groceryItem.charAt(0).toUpperCase() + groceryItem.slice(1)}s are $${groceryPrices[groceryItem]}` : 'Invalid item'; console.log(message);
1 Like

Hi !
I’m not sure how to use the switch :

let x = 15
switch (x) {
case (15) :
console.log(“Right”);
break;
case (<15) :
console.log(“Less”);
break;
case (>15) :
console.log(“More”);
break;
default :
console.log(“None”);
break;
}

Is it possible to use it this way ?

Not in the way you describe, no. But don’t stop investigating. Tear it down and analyze the types so that each expression, the switch and the case are the same.

Thank you for the quick reply ! For this one i know it’s incorrect as it shows error. To be more precise, i’ve seen examples of switch using strings but not numbers as in my example.

1 Like

Match the TYPE in both switch argument and case parameter. That is the key to mastering this device. It is only a device, and bears mastering, However, it is syntactic sugar, so should be given great consideration when usage comes into play. Make it make sense.

Working on it ! I have to work on my vocabulary too haha.

1 Like