Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

9 of 10
added link
user avatar
user avatar

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.

You can also 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
 ···
}

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';
 ...
}
Tom Ritter
  • 101.6k
  • 32
  • 143
  • 174

AltStyle によって変換されたページ (->オリジナル) /