JavaScript Switch Statements

 JavaScript Switch Statements

A switch statement in JavaScript is used to evaluate expressions. We already know what expressions are as we have used various operators such as equality comparison and athematic.

It matches the expressions value to the case clause to yield a true or false result.

If true, the case is executed, otherwise it's ignored. This happens until the switch finds a break keyword. Don't omit the break keyword. 

Values by default are checked with a strict equality which we have already studied.

Let's look at an example.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doers - Switch statement</title>
</head>
<body>
    <p id="result"></p>

<script>
  var expr = 'Mangos';
    switch (expr) {
    case 'Mangos':
        console.log("Mangoes cost 400 per kilo");
        break;
    case 'Kiwis':
       console.log("Kiwis cost 120 per kilo");
        break;
    case 'Oranges':
    console.log("Oranges cost 200 per kilo");
    break;    
    default:
    console.log("Sorry we are out of " + expr);
    }

</script>
</body>
</html>

Change the values to numbers, arrays, strings and play around to understand how this works.

 



Post a Comment

0 Comments

React