--- title: Default parameters slug: Web/JavaScript/Reference/Functions/Default_parameters translation_of: Web/JavaScript/Reference/Functions/Default_parameters ---
undefined
כערך, הערך הראשוני שהוגדר כברירת מחדל ישמש בתור הפרמטר של הפונקציה.
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements }
הערך ראשוני של פרמטר בפונקציה ב JavaScript שווה ל undefined
. אומנם ישנם מקרים בהם זה יכול להיות נוח להציב ערך שונה כערך ראשוני לפרמטר של הפונקציה, כך שהערך יוגדר מראש ביצירת הפונקציה. ופה אנחנו נעזרים בהצבת פרמטר ברירת מחדל לפונקציה.
האסטרטגיה הכללית שהשתמשו בה לפני פרמטר ברירת המחדל, היתה בדיקה שנכללה בתוך גוף הפונקציה ובדקה אם הפרמטר מכיל ערך או שהוא אינו מוגדר, ולא נעשה בו שימוש בקריאה לפונקציה. בדוגמא שלפנינו אם לא נעביר ערך ל b
בקריאה לפונקציה (בהפעלה שלה, בכל הפעלה לש פונקציה אנחנו קוראים לה מהזיכרון), היא תקבל ערך לא מוגדר (undefined
) וכאשר תיקראו לפונקציה multiply
כדי לחשב את a*b
התוצאה תהיה NaN
. לשם כך השורה השניה בפונקציה בודקת אם קיים בפרמטר b
ערך השונה מ undefined
ואם לא נעשה שימוש בפרמטר b
בקריאה לפונקציה אז מציבים בו ערך ראשוני של 1:
function multiply(a, b) { b = (typeof b !== 'undefined') ? b : 1; return a * b; } multiply(5, 2); // 10 multiply(5, 1); // 5 multiply(5); // 5
בעזרת הצבה של פרמטר ברירת מחדל לפונקציה הניתן לשימוש מגרסה ES2015 הבדיקה בגוף הפונקציה כבר לא נחוצה. עכשיו אפשר פשוט להציב ערך ראשוני כערך ברירת מחדל בהגדרה של הפונקציה והפרמטרים שלה:
function multiply(a, b = 1) { return a * b; } multiply(5, 2); // 10 multiply(5, 1); // 5 multiply(5); // 5
undefined
מול ערכים שליליים שונים.בהפעלה השניה של הפונקציה בדוגמה test
אנחנו מעבירים באופן מכוון ערך של undefined
והפרמטר num
עדיין מקבל את ערך ברירת המחדל שהגדרנו בעת יצירת הפונקציה (num = 1)
. ניתן לראות בקריאות הבאות לפונקציה, כי אך ורק undefined
זוכה להחלפה בערך ברירת המחדל ולא שום סוג של ערך שלילי אחר ( num === fale!!
).
function test(num = 1) { console.log(typeof num); } test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(''); // 'string' (num is set to '') test(null); // 'object' (num is set to null)
The default argument gets evaluated at call time, so unlike e.g. in Python, a new object is created each time the function is called.
function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]
This even applies to functions and variables:
function callSomething(thing = something()) { return thing; } function something() { return 'sth'; } callSomething(); //sth
Parameters already encountered are available to later default parameters:
function singularAutoPlural(singular, plural = singular + 's', rallyingCry = plural + ' ATTACK!!!') { return [singular, plural, rallyingCry]; } //["Gecko","Geckos", "Geckos ATTACK!!!"] singularAutoPlural('Gecko'); //["Fox","Foxes", "Foxes ATTACK!!!"] singularAutoPlural('Fox', 'Foxes'); //["Deer", "Deer", "Deer ... change."] singularAutoPlural('Deer', 'Deer', 'Deer peaceably and respectfully \ petition the government for positive change.')
This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.
function go() { return ':P'; } function withDefaults(a, b = 5, c = b, d = go(), e = this, f = arguments, g = this.value) { return [a, b, c, d, e, f, g]; } function withoutDefaults(a, b, c, d, e, f, g) { switch (arguments.length) { case 0: a; case 1: b = 5; case 2: c = b; case 3: d = go(); case 4: e = this; case 5: f = arguments; case 6: g = this.value; default: } return [a, b, c, d, e, f, g]; } withDefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] withoutDefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
Introduced in Gecko 33 {{geckoRelease(33)}}. Functions declared in the function body cannot be referred inside default parameters and throw a {{jsxref("ReferenceError")}} (currently a {{jsxref("TypeError")}} in SpiderMonkey, see {{bug(1022967)}}). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.
// Doesn't work! Throws ReferenceError. function f(a = go()) { function go() { return ':P'; } }
Prior to Gecko 26 {{geckoRelease(26)}}, the following code resulted in a {{jsxref("SyntaxError")}}. This has been fixed in {{bug(777060)}} and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.
function f(x = 1, y) { return [x, y]; } f(); // [1, undefined] f(2); // [2, undefined]
You can use default value assignment with the destructuring assignment notation:
function f([x, y] = [1, 2], {z: z} = {z: 3}) { return x + y + z; } f(); // 6
Specification | Status | Comment |
---|---|---|
{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}} | {{Spec2('ES2015')}} | Initial definition. |
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.functions.default_parameters")}}