Question

Override JavaScript default parameter with undefined

I have a function with argument bar that has a default parameter, "". How do I override bar's default parameter with value undefined?

const foo = (bar = "") => {
  console.log(bar)
}

foo(null) // null
foo(undefined) // "" <-- I want this to log `undefined`

If this is impossible with default parameters, what would be an appropriate way to write foo to achieve this?

 48  6835  48
1 Jan 1970

Solution

 47

what would be an appropriate way to write foo to achieve this?

If you mean to default only when there is no parameter passed to the function call, then you need to check the arguments length, or to spread the arguments if you want to keep an arrow function.

const foo = (...args) => {
  const bar = args.length ? args[0] : "";
  console.log(bar)
}

foo(null) // null
foo(undefined) // undefined
foo(); // ""

2020-05-06

Solution

 26

No, you can't, by design.

You've run into an interesting demonstration of JavaScript's 'two nulls', null and undefined.

null is a designated null value

undefined is the absence of any value at all

You ask about the passing the 'value' undefined but that premise is flawed. There is no value undefined - undefined is the lack of a value.

Therefore, you shouldn't pass undefined as a meaningful value to be interpreted by a function. I mean, you can, but from the point of view of JavaScript it is equivalent to passing nothing at all - so you're fighting against the design of the language and will run into issues like this one.

If you want to pass a meaningful, purposeful null value, that is what null is for.

2020-05-06