Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: optional first argument in function

Tags:

javascript

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

like image 825
salmane Avatar asked Jun 30 '10 08:06

salmane


People also ask

How do you pass optional arguments in JavaScript?

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.

Can you have optional arguments in JavaScript?

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.

What are optional function arguments?

Optional arguments are values that do not need to be specified for a function to be called.

How can we make a parameter of a function optional?

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.


2 Answers

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:

  1. Either change the order of your arguments, i.e. function(options, content)
  2. 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.

like image 126
Felix Kling Avatar answered Sep 24 '22 07:09

Felix Kling


my_function = function(hash) { /* use hash.options and hash.content */ }; 

and then call:

my_function ({ options: options }); my_function ({ options: options, content: content }); 
like image 22
Darin Dimitrov Avatar answered Sep 24 '22 07:09

Darin Dimitrov