Domenic Corso
Domenic Corso

Reputation: 55

JavaScript Switch Statements - possible to use case value?

I was wondering if it is possible to use something similar to 'this' in a Javascript switch statement when executing blocks of code.

For example:

switch(x) {
    case 'The pyramids of Giza':
        console.log(this);
        break;
    case 'The Leaning Tower of Pisa':
        console.log(this);
        break;
    default:
        console.log('Not found');
}

Is the same as:

switch(x) {
    case 'The pyramids of Giza':
        console.log('The pyramids of Giza');
        break;
    case 'The Leaning Tower of Pisa':
        console.log('The Leaning Tower of Pisa');
        break;
    default:
        console.log('Not found');
}

This is purely just for efficiency purposes, thanks!

Upvotes: 3

Views: 3036

Answers (4)

Michael Adebambo
Michael Adebambo

Reputation: 1

If you are returning the value in HTML you can write it like this

switch(x) {
    case 'The pyramids of Giza':
        return `<button class="badge text-white">${x}</button>`
        break;

    case 'The Leaning Tower of Pisa':
        return `<button class="badge text-blue">${x}</button>`
        break;
    default:
        console.log('Not Found');
}

Upvotes: 0

Noble Mushtak
Noble Mushtak

Reputation: 1784

When you visit a case:, the value of the value specified in the case: is always the variable put in the switch statement. This is because a case: is only visited if the variable is equal to the value specified in case: in the first place, so you know that if you've visited that case, then the value of the variable must be the same as the value specified in the case:. Thus, this is the code you're looking for:

switch(x) {
    case 'The pyramids of Giza':
        console.log(x);
        break;
    case 'The Leaning Tower of Pisa':
        console.log(x);
        break;
    default:
         console.log('Not found');
}

Upvotes: 3

David Thomas
David Thomas

Reputation: 253396

You have access to the variable that you're testing within the switch statement; after all, if x is equal to "The pyramids of Giza", then x must also be the value you wish to use within that case.

switch(x) {
    case 'The pyramids of Giza':
        console.log(x); // output: 'The pyramids of Giza'
        break;
    case 'The Leaning Tower of Pisa':
        console.log(x); // output: 'The Leaning Tower of Pisa'
        break;
    default:
        console.log('Not found');
}

Upvotes: 14

Frank
Frank

Reputation: 55

switch(x) {
    case 'The pyramids of Giza':
        console.log(x);
        break;
    case 'The Leaning Tower of Pisa':
        console.log(x);
        break;
    default:
        console.log('Not Found');
}

Should do the trick

Upvotes: 1

Related Questions