★ wanayoo — archive 1999 https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/returnNouvelle recherche | Portail wanayoo

return

by 1 contributor:

This translation is incomplete. Please help translate this article from English.

Оператор return завершает выполнение текущей функции и возвращает значение этой функции

Синаксис

return [[expression]]; 
expression
Возвращаеме выражение. Если expression не указан, то вместо него возвращается undefined.

Описание

При вызове оператора return в функции, выполнение этой функции прекращается. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. The following return statements all break the function execution:

return;
return true;
return false;
return x;
return x + y / 3;

Automatic semicolon insertion

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

return
a + b;

// is transformed by ASI into

return; 
a + b;

// Console warns "unreachable code after return statement".
Starting with Gecko 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37), a warning is shown in the console if unreachable code is found after a return statement.

Examples

return

The following function returns the square of its argument, x, where x is a number.

function square(x) {
   return x * x;
}

Interrupt a function

A function immediately stops at the point where return is called.

function counter() {
  for (var count = 1; ; count++) {  // infinite loop
    console.log(count + "A"); // until 5
      if (count === 5) {          
        return;
      }
      console.log(count + "B");  // until 4
    }
  console.log(count + "C");  // never appears
}

counter();

// Output:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A

Returning a function

See also the article about Closures.

function magic(x) {
  return function calc(x) { return x * 42 };
}

var answer = magic();
answer(1337); // 56154

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Стандарт Initial definition.
ECMAScript 5.1 (ECMA-262)
Определение 'Return statement' в этой спецификации.
Стандарт  
ECMAScript 2015 (6th Edition, ECMA-262)
Определение 'Return statement' в этой спецификации.
Стандарт  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Да) (Да) (Да) (Да) (Да)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Да) (Да) (Да) (Да) (Да) (Да)

See also

Метки документа и участники

Contributors to this page: The-Raven
Обновлялась последний раз: The-Raven,
Скрыть боковую панель