I can’t find the similiar problem, I guess it’s because i can’t find a correct question/answer.
I want to create a function that will use default values if there is not arguments passed when calling a function, if so, replace default values with the values passed in function’s parameters.
For example:
function openBlock(false){
// if parameter was passed with 'false' value, it will do this
// else it will put automatically a 'true' value to an function's argument
}
So if call a function openBlock() without any params, it will consider that it’s param true by default. If i call a function with argument false like openBlock(false) it will override the default behavior.
Thanks
There are various ways to do this in Javascript, though none are built in. The easiest pattern is:
But as @FelixKling notes, this won’t work in your case, as it will replace any false-y value (including explicitly setting the argument to
false) with the default. For boolean arguments that you want to default totrue, you need:When you’re dealing with more than one or two arguments, the best option is often to use a single
optionsorconfigargument and check for the existence of properties:If you’re using a library like jQuery or underscore, the
extendmethod makes it quite easy to set up an object with default values and then overwrite them with supplied values if they exist: