Javascript switch if statement

JavaScript Switch Statement

The switch statement is used to perform different actions based on different conditions.

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Syntax

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

Example

The getDay() method returns the weekday as a number between 0 and 6.

This example uses the weekday number to calculate the weekday name:

switch (new Date().getDay()) <
case 0:
day = «Sunday»;
break;
case 1:
day = «Monday»;
break;
case 2:
day = «Tuesday»;
break;
case 3:
day = «Wednesday»;
break;
case 4:
day = «Thursday»;
break;
case 5:
day = «Friday»;
break;
case 6:
day = «Saturday»;
>

The result of day will be:

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

The default Keyword

The default keyword specifies the code to run if there is no case match:

Example

The getDay() method returns the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), write a default message:

switch (new Date().getDay()) <
case 6:
text = «Today is Saturday»;
break;
case 0:
text = «Today is Sunday»;
break;
default:
text = «Looking forward to the Weekend»;
>

The result of text will be:

The default case does not have to be the last case in a switch block:

Example

switch (new Date().getDay()) <
default:
text = «Looking forward to the Weekend»;
break;
case 6:
text = «Today is Saturday»;
break;
case 0:
text = «Today is Sunday»;
>

If default is not the last case in the switch block, remember to end the default case with a break.

Common Code Blocks

Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:

Example

switch (new Date().getDay()) <
case 4:
case 5:
text = «Soon it is Weekend»;
break;
case 0:
case 6:
text = «It is Weekend»;
break;
default:
text = «Looking forward to the Weekend»;
>

Читайте также:  Javascript указатель на массив

Switching Details

If multiple cases matches a case value, the first case is selected.

If no matching cases are found, the program continues to the default label.

If no default label is found, the program continues to the statement(s) after the switch.

Strict Comparison

Switch cases use strict comparison (===).

The values must be of the same type to match.

A strict comparison can only be true if the operands are of the same type.

In this example there will be no match for x:

Example

let x = «0»;
switch (x) case 0:
text = «Off»;
break;
case 1:
text = «On»;
break;
default:
text = «No value found»;
>

Источник

Конструкция «switch»

Конструкция switch заменяет собой сразу несколько if .

Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.

Синтаксис

Конструкция switch имеет один или более блок case и необязательный блок default .

  • Переменная x проверяется на строгое равенство первому значению value1 , затем второму value2 и так далее.
  • Если соответствие установлено – switch начинает выполняться от соответствующей директивы case и далее, до ближайшего break (или до конца switch ).
  • Если ни один case не совпал – выполняется (если есть) вариант default .

Пример работы

Пример использования switch (сработавший код выделен):

Здесь оператор switch последовательно сравнит a со всеми вариантами из case .

Сначала 3 , затем – так как нет совпадения – 4 . Совпадение найдено, будет выполнен этот вариант, со строки alert( ‘В точку!’ ) и далее, до ближайшего break , который прервёт выполнение.

Если break нет, то выполнение пойдёт ниже по следующим case , при этом остальные проверки игнорируются.

В примере выше последовательно выполнятся три alert :

alert( 'В точку!' ); alert( 'Перебор' ); alert( "Нет таких значений" );

И switch и case допускают любое выражение в качестве аргумента.

let a = "1"; let b = 0; switch (+a)

В этом примере выражение +a вычисляется в 1 , что совпадает с выражением b + 1 в case , и следовательно, код в этом блоке будет выполнен.

Группировка «case»

Несколько вариантов case , использующих один код, можно группировать.

Для примера, выполним один и тот же код для case 3 и case 5 , сгруппировав их:

Теперь оба варианта 3 и 5 выводят одно сообщение.

Возможность группировать case – это побочный эффект того, как switch/case работает без break . Здесь выполнение case 3 начинается со строки (*) и продолжается в case 5 , потому что отсутствует break .

Тип имеет значение

Нужно отметить, что проверка на равенство всегда строгая. Значения должны быть одного типа, чтобы выполнялось равенство.

Для примера, давайте рассмотрим следующий код:

let arg = prompt("Введите число?"); switch (arg)
  1. Для ‘0’ и ‘1’ выполнится первый alert .
  2. Для ‘2’ – второй alert .
  3. Но для 3 , результат выполнения prompt будет строка «3» , которая не соответствует строгому равенству === с числом 3 . Таким образом, мы имеем «мёртвый код» в case 3 ! Выполнится вариант default .

Задачи

Напишите «if», аналогичный «switch»

Напишите if..else , соответствующий следующему switch :

Читайте также:  Html open file with link

Если совсем точно следовать работе switch , то if должен выполнять строгое сравнение ‘===’ .

Впрочем, для таких строк, подойдёт и обычное сравнение ‘==’ .

if(browser == 'Edge') < alert("You've got the Edge!"); >else if (browser == 'Chrome' || browser == 'Firefox' || browser == 'Safari' || browser == 'Opera') < alert( 'Okay we support these browsers too' ); >else

Обратите внимание: конструкция browser == ‘Chrome’ || browser == ‘Firefox’ . разбита на несколько строк для лучшей читаемости.

Но всё равно запись через switch нагляднее.

Источник

JavaScript Switch Statement

In this tutorial, we will learn how to use the switch statement and how to use it in javascript to control the flow of the program with example.

Switch statement javascript

The switch statement is a conditional statement (just like if..else) that allows the programmer to execute different blocks of code depending on the value of a variable.

The switch statement is a more flexible version of the if-else statement because it allows the programmer to execute different blocks of code depending on the value of a variable.

Let’s first look at a simple example of the switch statement and then we will its syntax and how to use it.

Syntax of switch statement

The syntax of the switch statement is as follows:

switch (expression/variable) < case expression1: // execute if expression1 = expression break; case expression2: // execute if expression2 = expression break; . default: // execute if no match >

Let us understand the above syntax step by step.

  1. The switch keyword is used to start the switch statement.
  2. The expression is the variable that we want to check.
  3. The case keyword is used to start a new case block (if the expression of the switch is equal to the case expression, then execute the code inside the block).
  4. The expression1 is the expression for case1.
  5. The break keyword is used to end each case block. If you do not use the break keyword, then execution will continue to the next case block.
  6. The default keyword is used to start the default block.
  7. The break keyword is used to end the default block.

Flowchart of switch statement

The flowchart below shows the flow of the switch statement.

switch statement flow diagram

Example of switch statement

Let us understand the example of the switch statement with examples.

let operation = "cube"; let num = 5; switch(operation)
let message = "Hello"; switch(message)

Let’s see how the above code works:

  • The first expression in a switch statement is evaluated to today’s day
  • Then the value found by evaluating the expression is matched with values in each case
  • if the value is matched then a block of code for that case is executed
  • then break command breaks through the switch statement.
  • In case no condition matched then the code block of the default section is executed

Javascript switch multiple cases

How will execute the switch statement for multiple cases?

The syntax of switch statement is as follows:

Читайте также:  Java thread завершение потока

To execute switch statement for multiple cases, use a break statement for the last case that is to be run.

For example, if you want to execute a switch statement for cases 1, 2, and 3 then do not use a break statement for the first 2 cases among 3 cases. Instead, use the break statement for the last case.

Let us understand with examples.

let fruit = "Orange"; switch(fruit)

Let’s see another example of a switch statement with multiple cases.

let marks = 75; switch (marks)

Javascript switch case multiple arguments

The switch statement can also handle multiple arguments. The multiple arguments should be separated by javascript operators to be evaluated as a single value.

let a = 4, b = 5; switch (a + b) < case a + b % 2: console.log("Expression1 matched"); case a / 2 + a ^ b + a * b / 2: console.log("Expression2 matched"); break; default: console.log("Expression not matched"); >

In above example, a + b is evaluated as 4 + 5 and a / 2 + a ^ b + a * b / 2 is evaluated as (4 + 5) % 2 + (4 ^ 5) + (4 * 5) / 2 and both expressions are matched.

How to call a function in switch case in javascript?

The function can be called at the place of expression if it returns a valid value. The function can be called in the expression as well as in the case block.

You can put your function calling code in the switch case. The function calling code should be in the curly braces <> .

function sum(a, b) < return a + b; >switch(10) < case sum(1, 2): console.log("sum(1, 2)"); break; case sum(6, 4): < let output = "sum(6, 4) = " + sum(6, 4); console.log(output); >break; default: console.log("default"); >

Javascript nested switch statement

Javascript nested switch statement is similar to nested if statement. The nested switch statement is used to match values with multiple cases.

Here is an example of the nested switch statement.

let a = 1, b = 3; switch (a) < case 1: switch (b) < case 2: console.log("a = 1, b = 2"); break; case 3: console.log("a = 1, b = 3"); break; default: console.log("a = 1, b did not match"); >break; case 2: console.log("a = 2"); break; default: console.log("a did not match"); >

Javascript switch statement vs if else

Javascript switch statement is less efficient than if-else statement. (see the example below)

The if-else statement is used when there are multiple cases to match. The switch statement is used when there are multiple cases to match and the cases are not mutually exclusive.

console.time('if else'); for (let i = 0; i < 9999999; i++) < if (i % 2 == 0) < >else < >> console.timeEnd('if else'); console.time('switch'); for (let i = 0; i < 9999999; i++) < switch (i % 2) < case 0: break; case 1: break; >> console.timeEnd('switch');

Output : result may vary on each run depending on the processor. But if-else is always more efficient.

if else vs switch

javascript fizzbuzz switch statement

The fizzbuzz algorithm is a simple programming task that tests your knowledge of the basic concepts of programming.

You can use the switch statement to implement the fizzbuzz algorithm.

function fizzbuzz(num) < switch (true) < case num % 3 === 0 && num % 5 === 0: return "fizzbuzz"; case num % 3 === 0: return "fizz"; case num % 5 === 0: return "buzz"; >> console.log(fizzbuzz(3)); console.log(fizzbuzz(5)); console.log(fizzbuzz(15));

Источник

Оцените статью