Underscore as a JavaScript variable?

Solution 1:

I've seen the underscore used to denote that the variable is a "don't care" variable. It means that it doesn't matter and isn't used at all.

In the case you pointed out, it was used to signify that his function had two arguments, but he only needed the second one.

Solution 2:

Underscore is a valid JS variable name. The parameter named _ in the above example can be used as any other variable.

However, it is usually used to indicate to subsequent (human) reader of the code that whatever passed in will not be used. (The author of the code can be evil/ignorant and use it in the function, though).

Solution 3:

As a beginner, I failed to gather the many aspects associated with this answer, which are scattered over the comments and other answers. So, I'll try to consolidate them below:

Firstly, in the mentioned piece of code, the underscore argument is used as follows:-

$(this).val('').attr('id', function(_, id) { return id + i });

From the jQuery documentation for the attr function here, there exists an overloaded form of attr which is .attr( attributeName, function ). The function in this form is described as

Type: Function( Integer index, String attr )

Hence, it expects two parameters. However, in our code, we need only the id, which happens to be the second parameter.

Now, because of the way JS handles function arguments, we cannot write it as function(id), as JS would map id to index (the first argument expected for function). Thus, the function we write needs to have two parameters.

Here, a standard convention comes into play. As mentioned here,

The underscore character (_) is used as a standard way to indicate an unused function argument.

However, this is only a convention and not a rule. We could name the unused argument as index or unused just as well. That is,

$(this).val('').attr('id', function(unused, id) { return id + i });

would be a valid equivalent.

Thus, such a usage of _ to substitute for an unused argument can be used for any other jQuery function that has a similar overridden form. For example, in this answer, we can see the usage of underscore in the call to $.text(). Just to confirm, $.text() has an overridden form that accepts a function with two arguments, as shown here.