• JavaScript
  • JavaScript
  • Tutorials and guides
  • Beginner's tutorials
    1. JavaScript Guide
      1. Loops and iteration
      2. Representing dates & times
      3. Working with objects
      4. Iterators and generators
      5. Asynchronous JavaScript
      6. Equality comparisons and sameness
      7. Meta programming
      8. AggregateError
      9. AsyncGenerator
      10. BigInt
      11. DataView
      12. encodeURI()
      13. escape() Deprecated
      14. Float16Array
      15. Generator
      16. Int8Array
      17. InternalError Non-standard
      18. Iterator
      19. NaN
      20. parseInt()
      21. ReferenceError
      22. SharedArrayBuffer
      23. Temporal Experimental
      24. Uint8ClampedArray
      25. unescape() Deprecated
      26. WeakSet
  • Assignment (=)
  • Bitwise AND (&)
  • Bitwise OR assignment (|=)
  • Comma operator (,)
  • Destructuring
  • Exponentiation (**)
  • Greater than (>)
  • import.meta.resolve()
  • Inequality (!=)
  • Less than (<)
  • Logical NOT (!)
  • Multiplication assignment (*=)
  • Nullish coalescing assignment (??=)
  • Optional chaining (?.)
  • Right shift (>>)
  • Strict inequality (!==)
  • this
  • Unsigned right shift (>>>)
  • yield*
  • Block statement
  • continue
  • export
  • for...in
  • if...else
  • let
  • try...catch
  • with Deprecated
  • get
  • The arguments object
    1. callee Deprecated
    2. extends
    3. Static initialization blocks
  • Character class escape: \d, \D, \w, \W, \s, \S
  • Input boundary assertion: ^, $
  • Modifier: (?ims-ims:...)
  • Quantifier: *, +, ?, {n}, {n,}, {n,m}
  • Errors
    1. RangeError: argument is not a valid code point
    2. RangeError: invalid array length
    3. RangeError: repeat count must be less than infinity
    4. ReferenceError: assignment to undeclared variable "x"
    5. SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
    6. SyntaxError: \ at end of pattern
    7. SyntaxError: await is only valid in async functions, async generators and modules
    8. SyntaxError: continue must be inside loop
    9. SyntaxError: function statement requires a name
    10. SyntaxError: identifier starts immediately after numeric literal
    11. SyntaxError: invalid assignment left-hand side
    12. SyntaxError: invalid class set operation in regular expression
    13. SyntaxError: invalid property name in regular expression
    14. SyntaxError: invalid unicode escape in regular expression
    15. SyntaxError: missing ) after argument list
    16. SyntaxError: missing } after property list
    17. SyntaxError: missing variable name
    18. SyntaxError: numbers out of order in {} quantifier.
    19. SyntaxError: property name __proto__ appears more than once in object literal
    20. SyntaxError: rest parameter may not have a default
    21. SyntaxError: super() is only valid in derived class constructors
    22. SyntaxError: unlabeled break must be inside loop or switch
    23. TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
    24. TypeError: "x" is not a function
    25. TypeError: BigInt value can't be serialized in JSON
    26. TypeError: can't convert BigInt to number
    27. TypeError: can't redefine non-configurable property "x"
    28. TypeError: class constructors must be invoked with 'new'
    29. TypeError: Initializing an object twice is an error with private fields/methods
    30. TypeError: Iterator/AsyncIterator constructor can't be used directly
    31. TypeError: property "x" is non-configurable and can't be deleted
    32. TypeError: X.prototype.y called on incompatible type
    33. JavaScript technologies overview
    34. Strict mode
    35. Learn more
    36. See full compatibility
  • Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

    Try it

    function multiply(a, b = 1) {
      return a * b;
    }
    
    console.log(multiply(5, 2));
    / Expected output: 10
    
    console.log(multiply(5));
    / Expected output: 5
    

    Syntax

    js
    function fnName(param1 = defaultValue1, /* …, */ paramN = defaultValueN) {
      / …
    }
    

    Description

    In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help.

    In the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return NaN.

    js
    function multiply(a, b) {
      return a * b;
    }
    
    multiply(5, 2); / 10
    multiply(5); / NaN !
    

    In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. In the following example, b is set to 1 if multiply is called with only one argument:

    js
    function multiply(a, b) {
      b = typeof b !== "undefined" ? b : 1;
      return a * b;
    }
    
    multiply(5, 2); / 10
    multiply(5); / 5
    

    With default parameters, checks in the function body are no longer necessary. Now, you can assign 1 as the default value for b in the function head:

    js
    function multiply(a, b = 1) {
      return a * b;
    }
    
    multiply(5, 2); / 10
    multiply(5); / 5
    multiply(5, undefined); / 5
    

    Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.

    js
    function f(x = 1, y) {
      return [x, y];
    }
    
    f(); / [1, undefined]
    f(2); / [2, undefined]
    

    Note: The first default parameter and all parameters after it will not contribute to the function's length.

    The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.

    This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time var-declared variables in the function body.

    For example, the following function will throw a ReferenceError when invoked, because the default parameter value does not have access to the child scope of the function body:

    js
    function f(a = go()) {
      function go() {
        return ":P";
      }
    }
    
    f(); / ReferenceError: go is not defined
    

    This function will print the value of the parameter a, because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b.

    js
    function f(a, b = () => console.log(a)) {
      var a = 1;
      b();
    }
    
    f(); / undefined
    f(5); / 5
    

    The default parameter allows any expression, but you cannot use yield that would pause the evaluation of the default expression. The parameter must be initialized synchronously.

    js
    async function f(a = await Promise.resolve(1)) {
      return a;
    }
    

    Note: Because the default parameter is evaluated when the function is called, not when the function is defined, the validity of the await and yield operators depends on the function itself, not its surrounding function. For example, if the current function is not async, await will be parsed as an identifier and follow normal identifier syntax rules, even when this function is nested in an async function.

    Examples

    Passing undefined vs. other falsy values

    In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.

    js
    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)
    

    Evaluated at call time

    The default argument is evaluated at call time. Unlike with Python (for example), a new object is created each time the function is called.

    js
    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:

    js
    function callSomething(thing = something()) {
      return thing;
    }
    
    let numberOfTimesCalled = 0;
    function something() {
      numberOfTimesCalled += 1;
      return numberOfTimesCalled;
    }
    
    callSomething(); / 1
    callSomething(); / 2
    

    Earlier parameters are available to later default parameters

    Parameters defined earlier (to the left) are available to later default parameters:

    js
    function greet(name, greeting, message = `${greeting} ${name}`) {
      return [name, greeting, message];
    }
    
    greet("David", "Hi"); / ["David", "Hi", "Hi David"]
    greet("David", "Hi", "Happy Birthday!"); / ["David", "Hi", "Happy Birthday!"]
    

    This functionality can be approximated like this, which demonstrates how many edge cases are handled:

    js
    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:
        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;
      }
      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, "=^_^="]
    

    Destructured parameter with default value assignment

    You can use default value assignment with the destructuring syntax.

    A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: [x = 1, y = 2] = []. This makes it possible to pass nothing to the function and still have those values prefilled:

    js
    function preFilledArray([x = 1, y = 2] = []) {
      return x + y;
    }
    
    preFilledArray(); / 3
    preFilledArray([]); / 3
    preFilledArray([2]); / 4
    preFilledArray([2, 3]); / 5
    
    / Works the same for objects:
    function preFilledObject({ z = 3 } = {}) {
      return z;
    }
    
    preFilledObject(); / 3
    preFilledObject({}); / 3
    preFilledObject({ z: 2 }); / 2
    

    Specifications

    Specification
    ECMAScript® 2026 Language Specification
    # sec-function-definitions

    Browser compatibility

    See also