[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Guide/Control_flow_and_error_handling [Back]  [Original]

- 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

JavaScript , , , . .

, , JavaScript. (;) .

(expression) JavaScript (statement). , .

In this article

block

block . :

{ statement_1; statement_2; ... statement_n; }

(, if, for, while).

js
while (x < 10) {
  x++;
}

{ x++; } .

: JavaScript ECMAScript2015. , , ( ), , . , . "" (standalone) JavaScript , C Java. :

js
var x = 1;
{
  var x = 2;
}
console.log(x); //  2

var x , var x . C Java 1.

ECMAScript 6, let . , let.

, , . JavaScript : if...else switch.

if...else

if , . else, , . if :

js
if (condition) {
  statement_1;
} else {
  statement_2;
}

condition , (true) (false). true false, Boolean. true, statement_1, - statement_2. statement_1 statement_2 , if.

, else if :

if (condition_1) { statement_1;} else if (condition_2) { statement_2;} else if (condition_n) { statement_n; } else { statement_last;}

, (true), . ({ ... }) . , if:

if (condition) {
  statement_1_runs_if_condition_is_true;
  statement_2_runs_if_condition_is_true;
} else {
  statement_3_runs_if_condition_is_false;
  statement_4_runs_if_condition_is_false;
}

, .. . , :

js
if (x = y) {
  /* ... */
}

, . :

js
if ((x = y)) {
  /* ... */
}

:

  • false
  • undefined
  • null
  • 0
  • NaN
  • ( "" )

, , .

true false true false Boolean. :

js
var b = new Boolean(false);
if (b) //   true
if (b == true) //   false

checkData true, Text ; alert false.

js
function checkData() {
  if (document.form1.threeChar.value.length == 3) {
    return true;
  } else {
    alert(
      "Enter exactly three characters. " +
        document.form1.threeChar.value +
        " is not valid.",
    );
    return false;
  }
}

switch

switch . :

switch (expression) {
   case label_1:
      statements_1
      [break;]
   case label_2:
      statements_2
      [break;]
   ...
   default:
      statements_default
      [break;]
}

case label, expression. , break, switch . default . default , , switch. default , .

break , , , , .

fruittype "Bananas", "Bananas are $0.48 a pound." break switch. break , , "Cherries", .. "Cherries are $3.00 a pound.".

js
switch (fruittype) {
  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":
    console.log("Mangoes are $0.56 a pound.");
    break;
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log("Sorry, we are out of " + fruittype + ".");
}
console.log("Is there anything else you'd like?");

throw , , try...catch, .

. , . , , :

throw

throw, . , , :

throw expression;

, . :

js
throw "Error2"; // string
throw 42; // number
throw true; // boolean
throw {
  toString: function () {
    return "I'm an object!";
  },
}; // object

: . catch.

: UserException :

js
function UserException(message) {
  this.message = message;
  this.name = "UserException";
}

UserException.prototype.toString = function () {
  return this.name + ': "' + this.message + '"';
};

throw new UserException("Value too high");

try...catch

try...catch try, , catch, , try. , try , catch. try , catch . finally try catch, , .

getMonthName, . , "InvalidMonthNo", catch:

js
function getMonthName(mo) {
  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
  var months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];
  if (months[mo]) {
    return months[mo];
  } else {
    throw "InvalidMonthNo"; //throw keyword is used here
  }
}

try {
  // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler -> your own
}

catch

catch, , try.

catch (catchID) { statements }

JavaScript catchID, , catch; catch .

, catch:

js
try {
  throw "myException";
} catch (e) {
  console.error(e);
}

finally

finally , try catch, , , try...catch. finally , . finally , catch.

, try writeMyFile, . , catch. closeMyFile, finally.

js
openMyFile();
try {
  writeMyFile(theData);
} catch (e) {
  handleError(e);
} finally {
  closeMyFile();
}

finally , try-catch-finally. , try catch, .

js
function f() {
  try {
    console.log(0);
    throw "bogus";
  } catch (e) {
    console.log(1);
    return true; //     `finally`
    console.log(2); //  
  } finally {
    console.log(3);
    return false; //   `return`
    console.log(4); //  
  }
  // `return false`  
  console.log(5); //  
}
f(); //  0, 1, 3   `false`

finally , catch:

js
function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    throw e; //     `finally`
  } finally {
    return false; //   `throw`
  }
  // `return false`  
}

try {
  f();
} catch (e) {
  //  , .. `throw`  `catch `  `return`  `finally`
  console.log('caught outer "bogus"');
}

//     caught inner "bogus"
//    `false`

try...catch

try...catch . try...catch catch, finally, catch. try-.

Error

name message, . name (, DOMException Error), message .

, , (, catch ), Error. :

js
function doSomethingErrorProne() {
  if (ourCodeMakesAMistake()) {
    throw new Error("The message");
  } else {
    doSomethingToGetAJavascriptError();
  }
}

try {
  doSomethingErrorProne();
} catch (e) {
  console.log(e.name); // 'Error'
  console.log(e.message); // 'The message'  JavaScript error message
}

Promise

ECMAScript2015, JavaScript Promise, .

Promise :

  • (pending): , .
  • (fulfilled): .
  • (rejected): .
  • (settled): , .

[]

XHR

Promise XMLHttpRequest MDN promise-test GitHub. . , Promise XHR. :

js
function imgLoad(url) {
  return new Promise(function (resolve, reject) {
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.responseType = "blob";
    request.onload = function () {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(
          Error(
            "Image didn't load successfully; error code:" + request.statusText,
          ),
        );
      }
    };
    request.onerror = function () {
      reject(Error("There was a network error."));
    };
    request.send();
  });
}

Web Proxy Viewer  |  New URL  |  Original Page