[javascript] Default argument values in JavaScript functions

Possible Duplicate:
How do I make a default value for a parameter to a javascript function

in PHP:

function func($a = 10, $b = 20){
  // if func() is called with no arguments $a will be 10 and $ b  will be 20
}

How can you do this in JavaScript?

I get a error if I try to assign values in function arguments

missing ) after formal parameters

This question is related to javascript function arguments

The answer is


In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);

ES2015 onwards:

From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,

function A(a, b = 4, c = 5) {
}

or combined with ES2015 destructuring,

function B({c} = {c: 2}, [d, e] = [3, 4]) {
}

For detailed explanation,

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Pre ES2015:

If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN, or null you can simply use

(So, for Objects, Arrays and Functions that you plan never to send null, you can use)

param || DEFAULT_VALUE

for example,

function X(a) {
  a = a || function() {};
}

Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ("", null, NaN, false, 0) too - which makes this method impossible to assign a param the falsy value passed as the argument.

So, in order to handle only undefined values explicitly, the preferred approach would be,

function C(a, b) {
  a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
  b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}

I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:

 function(a, b) {
      if (typeof a == "undefined") {
        a = 10;
      }

      if (typeof b == "undefined") {
        a = 20;
      }

      alert("a: " + a + " b: " + b);
    }

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.


You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

function func(a, b)
{
  if (typeof a == 'undefined')
    a = 10;
  if (typeof b == 'undefined')
    b = 20;
  // do what you want ... for example
  alert(a + ',' + b);
}

in shorthand

function func(a, b)
{
  a = (typeof a == 'undefined')?10:a;
  b = (typeof b == 'undefined')?20:b;

  // do what you want ... for example
  alert(a + ',' + b);
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python