When to use or not to use 'break' keyword in switch-case conditional statements

Hello to you all,

I’m currently doing the following exercise. for now everything seems to be fine, I’m just confused by the issue mentioned in the title:



The programmer girl, as I learned, after each case ‘locks’ with ‘break’.
In addition, she also mentions and emphasizes, not to forget to end each ‘case’ with a ‘break’.

In contrast, in the exercise before it:


The guy does not use ‘brake’.
I noticed this in retrospect, in the middle of the exercise that the girl demonstrates.

At first I thought that maybe using the ‘return’ is exempt from using the brake, or maybe conditioning within a function obviates this use (as was also assumed in the YouTube comments to the first video), but I was deceived because the two cases are the same.

Also in the current exercise I am in, the girl wants to use ‘break’ despite using return.

I would love to receive clarification.

Thank you.

I guess they’re both right, in that they’ll work, but the first including break, i’d say, would be more robust.
The return statement means the sections of code will end before they reach the break in each case, so it’s more or less redundant. The issue comes if you decide to change the code later.
Where there’s one line of code for each case it might not be too important, but with a more involved code block you may tweak something which means it’s not guaranteed to hit a return statement for each case. Without a break it’ll try and run code it’s not supposed to and give you a headache trying to decipher where the issue is.
So, I’d says it’s a good habit to include it as it makes the code more predictable and easier to follow.

Hi pluginmaybe,

Thank you, indeed, after some tests I did, it seems that using return ‘captures’ or catches only the desired exact output anyway, even without the use of break.

I took an example from the study material from the beginning of the chapter (I just shortened it a bit):

let groceryItem = ‘tomato’;

switch (groceryItem) {
case ‘tomato’:
console.log(‘Tomatoes are $0.49’);
case ‘lime’:
console.log(‘Limes are $1.49’);
console.log(‘Invalid item’);

Removing any ‘break’ in this mode, as expected, caused all subsequent conditions after case ‘tomato’ to be executed even if they are false.
When I added ‘return’ before each ‘console.log’ like this:
return console.log(‘Tomatoes are $0.49’);

Only the line that is true, was executed.

In principle, for general knowledge, it is possible that non-use ‘break’ in such cases may result in security breaches?

Thanks alot.