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?
Bookmark this question. Show activity on this post. In the following code, call to Method2 receives the Value parameter as False, even though base class does not declare default value for the parameter at all, and derived class declares True as default.
See, undefined is passed as argument, but not passed as a parameter when we invoke the function. So, inside the function the value of the variable undefined is (guaranteed) the original value of undefined .
Yes, it is correct that you can assign a default value to the parameter before calling the function, which results in you not needing to pass an argument when calling the function. The default parameter is however always overridden if you pass a value to the function.
Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
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(); // ""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With