I have a typical javascript function with some parameters
my_function = function(content, options) { action }
if I call the function as such :
my_function (options)
the argument "options" is passed as "content"
how do i go around this so I can either have both arguments passed or just one ? thank you
To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.
Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.
Optional arguments are values that do not need to be specified for a function to be called.
Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. Without using keyword arguments. By using keyword arguments.
You have to decide as which parameter you want to treat a single argument. You cannot treat it as both, content
and options
.
I see two possibilities:
function(options, content)
Check whether options
is defined:
function(content, options) { if(typeof options === "undefined") { options = content; content = null; } //action }
But then you have to document properly, what happens if you only pass one argument to the function, as this is not immediately clear by looking at the signature.
my_function = function(hash) { /* use hash.options and hash.content */ };
and then call:
my_function ({ options: options }); my_function ({ options: options, content: content });
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