Javascript return method name

return

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

Интерактивный пример

Синтаксис

Выражение, значение которого будет возвращено. Если не указано, вместо него возвращается undefined .

Описание

При вызове оператора return в функции её выполнение прекращается. Указанное значение возвращается в место вызова функции. Например, приведённая ниже функция возвращает возведённое в квадрат значение своего аргумента, x (где x – это число):

function square(x)  return x * x; > var demo = square(3); // значение demo будет равняться 9 

Если возвращаемое значение не указано, вместо него возвращается undefined .

Следующие выражения всегда прерывают выполнение функции:

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

Автоматическая расстановка точек с запятыми

На выражение return влияет автоматическая расстановка точек с запятыми (ASI). Разрыв строки не допускается между ключевым словом return и выражением.

В консоли появится предупреждение «unreachable code after return statement».

Примечание: Начиная с Gecko 40, предупреждение в консоли появляется, если обнаружен недостижимый код после return .

Для того, чтобы избежать данной проблемы (предотвратить ASI), можно использовать скобки:

Примеры

Прерывание функции

Функция немедленно останавливается в точке, где вызывается return .

function counter()  for (var count = 1; ; count++)  // бесконечный цикл console.log(count + "A"); // до 5 if (count === 5)  return; > console.log(count + "B"); // до 4 > console.log(count + "C"); // никогда не появляется > counter(); // Выводит: // 1A // 1B // 2A // 2B // 3A // 3B // 4A // 4B // 5A 

Возвращение функции

function magic(x)  return function calc(x)  return x * 42 >; > var answer = magic(); answer(1337); // 56154 

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 17 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript return

The return statement stops the execution of a function and returns a value.

Read our JavaScript Tutorial to learn all you need to know about functions. Start with the introduction chapter about JavaScript Functions and JavaScript Scope. For more detailed information, see our Function Section on Function Definitions, Parameters, Invocation and Closures.

Syntax

Parameters

More Examples

Calculate the product of two numbers and return the result:

// Call a function and save the return value in x:
var x = myFunction(4, 3);

function myFunction(a, b) // Return the product of a and b
return a * b;
>

Browser Support

return is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Python e commerce cms
Оцените статью