How to Switch String in JavaScript
A switch-case
statement is identical to the conditional
statement. The difference between both functions is just in the syntax.
The switch
statement evaluates an expression and its type and then matches it with the declarative case
clause. The matching is operated by the ===
strict equal operation.
The triple equal ===
will only infer to a match that is solid in types and cases. This only results in Boolean, so either our clause matches the switch expression or follows up the default
section.
Satisfy case
Clause With switch
String
We will initiate a variable with a string
and pass this expression to this example’s switch
statement. Next, the switch
statement will compare the case
clause and the expression it possesses.
If the match returns true
, the code line for that certain code block will operate.
Code Snippet:
var str = 'butter';
switch (str) {
case 'butter':
console.log('Buttery delicious!');
break;
case 'chocolate':
console.log('Ain\'t chocolate everyones fav!');
break;
default:
console.log('What\'s wrong with your tastebud?');
}
Output:
Satisfy case
Clause by Typecast String Expression in switch
We will create a variable with a number,
but when we pass it as an expression for the switch
statement, we will perform the type conversion
.
It will not go for the default
case if the switch
statements expression and the case
clauses explicit conditions are of the same data type.
If you don’t know the type of expression, try to convert it to string
or any other preferable type for a certain case. Often in development, you might face the this
object instance, and when you follow the switch(this)
, you may get an error.
Even if it is an instance yet, it’s different from a string primitive. So, you have to explicitly define it this way: switch(String(this))
.
Code Snippet:
var val = 42;
switch (String(val)) {
case 1:
case 2:
case 3:
case 42:
console.log('It\'s a digit');
break;
default:
console.log('OOPS! This is string');
}
Output: