Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard conventions for indicating a function argument is unused in JavaScript

Are there any standard ways of marking a function argument as unused in JavaScript, analogous to starting a method argument with an underscore in Ruby?

like image 956
Andrew Grimm Avatar asked Aug 25 '15 07:08

Andrew Grimm


People also ask

What are function arguments in JavaScript?

Arguments are Passed by ValueThe parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

What is the type of argument in a function JavaScript?

The arguments is an object which is local to a function. You can think of it as a local variable that is available with all functions by default except arrow functions in JavaScript. This object (arguments) is used to access the parameter passed to a function. It is only available within a function.

What are arguments and parameters in JavaScript?

Note the difference between parameters and arguments: Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.


2 Answers

Just so we have an example to work from, this is fairly common with jQuery's $.each where you're writing code that doesn't need the index, just the value, in the iteration callback ($.each is backward relative to Array#forEach):

$.each(objectOrArrayLikeThing, function(_, value) { }     // Use value here }); 

Using _ is the closest I've seen to a standard way to do that, yes, but I've also seen lots of others — giving it a name reflective of its purpose anyway (index), calling it unused, etc.

If you need to ignore more than one parameter, you can't repeat the same identifier (it's disallowed in strict mode, which should be everyone's default and is the default in modules and class constructs), so you have do things like _0 and _1 or _ and __, etc.

like image 151
T.J. Crowder Avatar answered Sep 21 '22 06:09

T.J. Crowder


Using destructuring assignment, one can do:

function f(...[, , third]) {    console.log(third);  }    f(1, 2, 3);
like image 39
Joseph Marinier Avatar answered Sep 22 '22 06:09

Joseph Marinier