Standard conventions for indicating a function argument is unused in JavaScript

JavascriptNaming ConventionsUnused Variables

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Using destructuring assignment, one can do:

function f(...[, , third]) {
  console.log(third);
}

f(1, 2, 3);

Solution 3 - Javascript

With browsers supporting destructuring one can do:

function ({}, {}, value) {
  // console.log(value)
}

Which is kind of neat in that it avoids the problem of multiple arguments having the same name and also won't create problems with libraries that assign methods to _ (lodash, underscore, etc.).

One problem with this approach is that unused arguments of type undefined or null will throw.

For undefined one solution is to use default parameters:

function ({}={}, {}={}, value) {
  // console.log(value)
}

Sadly no such easily applied solution for null.

Solution 4 - Javascript

I would recommend this syntax:

function(_index, value) {...}

to not to shadow lodash variable and still have description of argument in case if it will be used.

VS Code is also highlight these names properly and these unused args won't be deleted after autofix code smells

Solution 5 - Javascript

How about using the function arguments object?

function third() { const [,,thirdArg] = arguments;
  return thirdArg;
}
console.log(third(1,2,3));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew GrimmView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptJoseph MarinierView Answer on Stackoverflow
Solution 3 - JavascriptFredrik CarlssonView Answer on Stackoverflow
Solution 4 - JavascriptMarkosyanArturView Answer on Stackoverflow
Solution 5 - JavascriptDoug CoburnView Answer on Stackoverflow