Wednesday, 29 April 2020

Set a default parameter value for a JavaScript function

From ES6/ES2015, default parameters are in the language specification.
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 ··· }

Pre ES2015,

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

Referensi

  1. Set a default parameter value for a JavaScript function, https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function