The switch statement

The switch statement is used to move control to a specific inner case clause that specifies a value that matches the value passed to switch(...). It has the following syntax:

switch (SwitchExpression) SwitchBody

SwitchExpression will be evaluated once and its value compared via strict-equality to case statements within SwitchBody. Within SwitchBody there may be one or more case clauses and/or a default clause. The case clauses designate CaseExpression, whose value will be compared to that of SwitchExpression, and their syntax is as follows:

case CaseExpression:
[other JavaScript statements or additional clauses]

The switch statement is usually used to specify a selection of two or more mutually exclusive outcomes based on a specific value. With fewer conditions, it'd be conventional to use an if...else construct, but to accommodate more potential conditions, it's simpler to use switch:

function generateWelcomeMessage(language) {

let welcomeMessage;

switch (language) {
case 'DE':
welcomeMessage = 'Willkommen!';
break;
case 'FR':
welcomeMessage = 'Bienvenue!';
break;
default:
welcomeMessage = 'Welcome!';
}

return welcomeMessage;
}

generateWelcomeMessage('DE'); // => "Willkommen!"
generateWelcomeMessage('FR'); // => "Bienvenue!"
generateWelcomeMessage('EN'); // => "Welcome!"
generateWelcomeMessage(null); // => "Welcome!"

Once the switch mechanism finds the appropriate caseit will execute all code following that case statement until the very end of the switch statement or until it encounters a break statement. A break statement is used to break out of SwitchBody when the desired work is accomplished.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.242.165