Nullish coalescing syntax for default param values

Would there be any support for the idea of accepting nullish-colescing type of syntax for the default parameter values?

The syntax would use the provided default value for both null and undefined param values, just like nullish

In this example:

function setColor(color ?? '#aaa') { }

would be similar to:

function setColor(color = '#aaa') { }

except it would not only handle color equal to undefined but also null, just like : const foo = null ?? 'default string'

Of course the syntax would apply to each parameter in case of multiple parameter functions.

Supporting this would result in much simpler code, where you need to guard your code against null values. An example could be Angular where resetting form controls results in their value being null rather than undefined. Should you want to process the values for other purpose, you need to capture the nulls properly.

Also, the proposal seems like a very legit counterpart of the already supported object nullish coalescing in assignments - all in all, a default parameter is also an assignment.

I think the current

function setColor(color) {
  color ??= '#aaa';
  …
}

is better to read than cramming all the logic in the default initialisers. Also I prefer the concept of parameter defaults applying only when you pass no value (to which passing undefined is equivalent), instead of supporting guards to deal with nullish, falsy, non-object or non-iterable values.

I understand where you are coming from, but personally I don't see defaults as equivalent to assignments.

1 Like

There is an on-going issue on the proposal ^

I would also vote to not change the built-in semantics of default arguments.

2 Likes