Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip arguments in a JavaScript function

Tags:

javascript

I have a function like this:

function foo(a, b, c, d, e, f) { } 

In order to call this function only with an f argument, I know I should do:

foo(undefined, undefined, undefined, undefined, undefined, theFValue); 

Is there a less verbose way to do this?

Solutions:
I selected some proposed solutions (without using helper third functions)

// zero - ideal one, actually not possible(?!) foo(f: fValue);  // one - asks a "strange" declaration var _ = undefined; foo(_, _, _, _, _, fValue);  // two - asks the {} to be used instead of a 'natural' list of args //     - users should be aware about the internal structure of args obj //       so this option is not 'intellisense friendly' function foo(args){     // do stuff with `args.a`, `args.b`, etc. }     foo({f: fValue}); 
like image 734
serge Avatar asked Sep 11 '15 08:09

serge


People also ask

How do you skip a function in JavaScript?

js skip() Method. The skip() method is used to skip the given number of elements from collection and returns the remaining collection elements. Parameters: The collect() method takes one argument that is converted into the collection and then skip() method is applied on it.

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 is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

CAN default arguments be skipped?

It's not possible to skip it, but you can pass the default argument using ReflectionFunction .


1 Answers

Such:

foo(undefined, undefined, undefined, undefined, undefined, arg1, arg2); 

.is equal to:

foo(...Array(5), arg1, arg2); 

.or:

foo(...[,,,,,], arg1, arg2); 

Such:

foo(undefined, arg1, arg2); 

.is equal to:

foo(...Array(1), arg1, arg2); 

.or:

foo(...[,], arg1, arg2); 

Such:

foo(arg1, arg2); 

.is equal to:

foo(...Array(0), arg1, arg2); 

.or:

foo(...[], arg1, arg2); 
like image 111
Pacerier Avatar answered Sep 29 '22 14:09

Pacerier