Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

JavaScript - switch statement with example

0 contributions
4 points

switch statement is used to select and execute some code block from defined cases using expression.

1. switch syntax

switch(expression) {
    case x:
        // code block
        break;
    case y:
        // code block
        break;
    case z:
        // code block
        break;

    // other cases...

    default:
        // code block
}

Where:

  • expression returns value that will be compared with cases,
  • x, y and z are values that are associated with code blocks,
  • if expression maches some case value (x, y or z) than related code block is executed,
  • if break instruction is placed after code block, next code block is not executed,
  • if expression is not matched to any case value default code block is executed.

2. switch statement example

var name = 'John';
var role = '';

switch (name) {
    case 'John':
        role = 'Administrator';
        break;
    case 'Kate':
    case 'Chris':
        role = 'Moderator';
        break;
    default:
        role = 'User';
        break;
}

console.log('User ' + name + ' is ' + role + '.');

Output:

User John is Administrator.

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more