Tag: Default Parameter

Set a default parameter value for a JavaScript function

First Solution

From ES6/ES2015, default parameters is in the language specification.

function read_file(file, delete_after = false) {
  // Code
}

just works.

Reference: Default Parameters – MDN

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

Pre ES2015,

There are a lot of ways, but this is my preferred method – it lets you pass in anything you want, including false or null. (typeof null == "object")

function foo(a, b)
{
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}

Another Solution

To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.

function read_file(file, delete_after = false) {
    #code
}

In that example Edge will throw an error “Expecting ‘)'”

To get around this use

function read_file(file, delete_after) {
  if(delete_after == undefined)
  {
    delete_after = false;
  }
  #code
}

As of Aug 08 2016 this is still an issue

 

#Copied

Reference link: http://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function

Advertisements