Search code examples
javascriptdefault-parameters

Is having the first JavaScript parameter with default value possible?


It's practical to have the last parameter with a default value, as follows.

function add(x, y = 5) {
    return x + y;
}

console.log(add(3)); // results in '8'

However, is it possible to have other than the last parameter with a default value? If so, how would you call it with the intention of using the first default value, but providing the second parameter?

function add(x = 5, y) {
    return x + y;
}
    
console.log(add(,3)); // doesn't work

Solution

  • You still could keep your add function the same by call it with params from destructed array like below snippet

    function add(x = 5, y) {
      return x + y;
    }
    
    console.log(add(...[,3]));