I have a doubt, I have created a basic function in JavaScript and I have no idea why this function works normally with break and without break .
When is it necessary to use that break in the switch conditional structure ?
This is the function:
function translator( num )
{
switch ( num )
{
case 1:
return 'one';
case 2:
return 'two';
case 3:
return 'three';
case 4:
return 'four';
case 5:
return 'five';
default:
return 'Enter a number!';
}
}
let value = parseInt( prompt( 'Enter the number: ' ) );
let translateValue = translator( value );
document.write( translateValue );
If you look at the example that I put below, here if the break is necessary:
The reason is as follows:
In short, the break is used so that the script exits the execution (in this case) of the switch and does not evaluate the other conditions.
In my example, if you remove the breaks, you will see that the switch will evaluate your number, but it will always end up returning the default, since that condition will also return true.
I hope I have explained myself correctly.