Switch statement in javascript

Image byAlltechbuzz_net fromPixabay

Logically,switch statement inJavaScript is nothing but a combination of if-else statements. switch statement evaluates an expression and executes a matchingcase block. It may or may not havedefaultclause. Let’s see it in detail.

Syntax

switch(x) {  case 'value1':      ...    [break]  case 'expression':      ...    [break]  default:    ...    [break]}

value of ‘x’ will be checked against each case starting from 1st case, and if avalue is matched with any case, then that block will be executed until thebreakstatement occurs. Please note that thecase clause is optional, switch statement may or may not have anycase clause.

default clause is optional, it gets executed when no case is matched. switch statement in javascript will have only one default clause.

Importance of ‘break’ statement

To understand the importance of break statement, let’s see the following example first.

See the Pen Untitled by Code Topology (@codetopology) onCodePen.

The above code has 3 case clauses, which will evaluate their condition against variable ‘a’. In this case, even if ‘case 10‘: is matched and its block is executed, program flow will continue ‘case 11‘ block execution irrespective of the match.

To avoid this unexpected result, you should use ‘break‘ statement wherever needed.

Example

See the Pen Untitled by Code Topology (@codetopology) onCodePen.

As you can see, we can also use expressions in case clauses. In this case,case 5+5 will get executed.

Lexical Scope Handling

See the Pen javascript lexical scope issue by Code Topology (@codetopology) onCodePen.

The above code will throwUncaught SyntaxError: Identifier ‘alertStatement’ has already been declared Error.

This is because variablealertStatementis already declared in case “js” clause as aconst, and only one constant variable can be declared in one block scope. This means that all case clauses under switch statement share a common scope.

If there is a necessity where you need to declareconst variable repeatedly in a switch statement, you can use { } brackets to define its scope as shown in the following example:

See the Pen switch lexical scope issue resolved by Code Topology (@codetopology) onCodePen.

I hope you liked the article 🙂

Leave a ReplyCancel reply

Your email address will not be published.Required fields are marked*