הצהרה באמצעות return
מתבצעת בעת סיום הפונקציה, גורמת לעצירתה ומציינת ערך שיש להחזיר למבקש הפונקציה.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
תחביר
return [[expression]];
expression
- הביטוי שערכו יוחזר. במידה והביטוי לא הוזכר, הערך
undefined
יוחזר במקומו.
תיאור
השימוש בהצהרה return
בגוף הפונקציה, יפסיק את תהליך הריצה שלה.
לדוגמה, לפונקציה ()square
ארגומנט בשם x, כאשר x יהיה מספר הפונקציה תחזיר את הערך של הארגומנט כפול עצמו.
function square(x) {
return x * x;
}
var demo = square(3);
// demo will equal 9
במידה וארגומנט חסר, הערך שיוחזר יהיה undefined
.
הצהרות ה-return
הבאות מפסיקות את הריצה של הפונקציה:
return;
return true;
return false;
return x;
return x + y / 3;
הוספת נקודה פסיק באופן אוטומטי
להצהרה באמצעות return
מתווספת באופן אוטומטי נקודה פסיק (ASI).
אין לקשר בין שורת ההצהרה של return
לביטוי .
return
a + b;
return;
a + b;
כדי להימנע ממצב של הוספת נקודה פסיק באופן אוטומטי, יש להוסיף סוגריים באופן הבא:
return (
a + b
);
דוגמאות
עצירת הפונקציה
הפונקציה נעצרת מיד בעת הקריאה ל-return
.
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
החזרת פונקציה
ראו את המאמר הבא בנושא Closures.
function magic() {
return function calc(x) { return x * 42; };
}
var answer = magic();
answer(1337); // 56154
מפרט
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
ECMAScript 5.1 (ECMA-262) The definition of 'Return statement' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Return statement' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Return statement' in that specification. |
Living Standard |
תאימות דפדפן
BCD tables only load in the browser