[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/switch [Back]  [Original]

switch - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

switch

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

switch , , .

In this article

switch (expression) {
  case value1:
    //  ,     value1
    [break;]
  case value2:
    //,  value2
    [break;]
  ...
  case valueN:
    //,   valueN
    //statementsN
    [break;]
  default:
    //  ,      
    //statements_def
    [break;]
}
expression

, .

case valueN

, (expression).

statementsN

, , expression .

statements_def

, expression .

- , . , .

, ( , ===) , . , (default), . , , switch. , default , .

break switch. , . , switch.

: switch

, expr "Bananas", "Bananas" . break, switch. break , "Cherries".

js
switch (expr) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log("Sorry, we are out of " + expr + ".");
}

console.log("Is there anything else you'd like?");

: , break?

break, . .

js
var foo = 0;
switch (foo) {
  case -1:
    console.log("negative 1");
    break;
  case 0: // foo  0,        
    console.log(0);
  // :      break
  case 1: //   'case 0:'   break,      
    console.log(1);
    break; //    break,       'case 2:'
  case 2:
    console.log(2);
    break;
  default:
    console.log("default");
}

case

, case case , case . " , break?.

case , .

js
var Animal = "Giraffe";
switch (Animal) {
  case "Cow":
  case "Giraffe":
  case "Dog":
  case "Pig":
    console.log("This animal is not extinct.");
    break;
  case "Dinosaur":
  default:
    console.log("This animal is extinct.");
}

case, . , , case. . case .

js
var foo = 1;
var output = "Output: ";
switch (foo) {
  case 0:
    output += "So ";
  case 1:
    output += "What ";
    output += "Is ";
  case 2:
    output += "Your ";
  case 3:
    output += "Name";
  case 4:
    output += "?";
    console.log(output);
    break;
  case 5:
    output += "!";
    console.log(output);
    break;
  default:
    console.log("Please pick a number from 0 to 5!");
}

:

foo is NaN or not 1, 2, 3, 4, 5, or 0 Please pick a number from 0 to 5!
0 Output: So What Is Your Name?
1 Output: What Is Your Name?
2 Output: Your Name?
3 Output: Name?
4 Output: ?
5 Output: !

Specification
ECMAScript 2027 LanguageSpecification
# sec-switch-statement


Web Proxy Viewer  |  New URL  |  Original Page