HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Set a default parameter value for a JavaScript function

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionsetparameterforvaluejavascriptdefault

Problem

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:

def read_file(file, delete_after = false)
  # code
end


Does this work in JavaScript?

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

Solution

From ES6/ES2015, default parameters are 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.

In ES6, you can simulate default named parameters via destructuring:

// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}

// sample call using an object
myFor({ start: 3, end: 0 });

// also OK
myFor();
myFor({});


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';
  ...
}

Code Snippets

function read_file(file, delete_after = false) {
  // Code
}
// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}

// sample call using an object
myFor({ start: 3, end: 0 });

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

Context

Stack Overflow Q#894860, score: 3597

Revisions (0)

No revisions yet.