shunshun
shunshun

Reputation: 93

What is the proper way of adding an optional parameter to a function if function has only one param?

I have a function that I need to use it in onClick action and other part of the code as well. I'm trying to create an optional parameter. The optional param returns a class object instead of false value.

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
  .html('Click me') // Try edit it...
  .on('click', test)

returns:

{
originalEvent:[object PointerEvent],
type:"click",
isDefaultPrevented:f returnFalse {...},
target:<button class="btn btn-warning m-auto"></button>,
currentTarget:<button class="btn btn-warning m-auto"></button>,
relatedTarget:null,
timeStamp:2798.800000000745,
jQuery36007002776368131782:true,
delegateTarget:<button class="btn btn-warning m-auto"></button>,
handleObj: {...},
data:undefined
}``` 

Upvotes: 0

Views: 146

Answers (1)

FZs
FZs

Reputation: 18619

The problem is by passing the function to jQuery#on() as is, it will receive all arguments on passes to it.

It's like doing this:

//            vvvvvvv----------vvvvvvv--- Get all arguments that `on` passes and pass them to `test`
.on('click', (...args) => test(...args))

And, jQuery#on() does pass an argument to your function, the event object, so it won't fall back to using the default value.

If you want to avoid that, you could just create an anonymous wrapper around your function, that doesn't forward the arguments to test:

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
  .html('Click me')
  //                     vv--- Pass nothing in here
  .on('click', () => test())

Upvotes: 1

Related Questions