Is having the first JavaScript parameter with default value possible?

Viewed 1517

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
2 Answers

You still need to provide the first parameter regardless of its default value.

Try destructuring a single parameter instead, like this:

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

console.log(add({ y: 3 })); // results in '8'

You will still have to specify the y key, though, but this is a way better practice.

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]));

Related