_=> What Does This Underscore Mean in Lambda Expressions

Underscore Arrow (_ = ...) What Is This?

It's just a lambda expression that uses _ instead of x for its parameter. _ is a valid identifier so it can be used as a parameter name.

As mentioned in the comments, it's a convention among some developers to call it _ to indicate that it's not actually used by the lambda expression, but it's no more than that: a convention.

Note that this is not the same thing as a discard (introduced several years after this answer), which is a special variable for assigning values that aren't going to be used and will instead be discarded. Unlike discarded values, _ parameters continue to exist in lambda scope; they just aren't used anywhere in the lambda expression. And there can only be one _ in scope at a time.

C# style: Lambdas, _ = or x =?

Many C# developers use _ to indicate that the parameter isn't going to be used and a letter or other short name when the parameter is being used.

Other resources:

  • Interesting discussion on using _ instead of ()

Using _ (underscore) variable with arrow functions in ES6/Typescript

The reason why this style can be used (and possibly why it was used here) is that _ is one character shorter than ().

Optional parentheses fall into the same style issue as optional curly brackets. This is a matter of taste and code style for the most part, but verbosity is favoured here because of consistency.

While arrow functions allow a single parameter without parentheses, it is inconsistent with zero, single destructured, single rest and multiple parameters:

let zeroParamFn = () => { ... };
let oneParamFn = param1 => { ... };
let oneParamDestructuredArrFn = ([param1]) => { ... };
let oneParamDestructuredObjFn = ({ param1 }) => { ... };
let twoParamsFn = (param1, param2) => { ... };
let restParamsFn = (...params) => { ... };

Although is declared but never used error was fixed in TypeScript 2.0 for underscored parameters, _ can also trigger unused variable/parameter warning from a linter or IDE. This is a considerable argument against doing this.

_ can be conventionally used for ignored parameters (as the other answer already explained). While this may be considered acceptable, this habit may result in a conflict with _ Underscore/Lodash namespace, also looks confusing when there are multiple ignored parameters. For this reason it is beneficial to have properly named underscored parameters (supported in TS 2.0), also saves time on figuring out function signature and why the parameters are marked as ignored (this defies the purpose of _ parameter as a shortcut):

let fn = (param1, _unusedParam2, param3) => { ... };

For the reasons listed above, I would personally consider _ => { ... } code style a bad tone that should be avoided.

_ (underscore) is a reserved keyword

The place to look is JLS §15.27.1. Lambda Parameters

It is a compile-time error if a lambda parameter has the name _ (that is, a single underscore character).

The use of the variable name _ in any context is discouraged. Future versions of the Java programming language may reserve this name as a keyword and/or give it special semantics.

So the Eclipse message is misleading, especially as the same message is used for both cases, when an error is generated for a lambda parameter or when a warning is generated for any other _ identifier.

(_) = DoWork(); How an underscore is valid as a anonymous delegate parameter?

An underscore is a normal identifier character in C#. For example my_money is valid. So _ is just as valid as x.

You could also write _ => DoWork() which I think is more common.

Python's lambda with underscore for an argument?

The _ is variable name. Try it.
(This variable name is usually a name for an ignored variable. A placeholder so to speak.)

Python:

>>> l = lambda _: True
>>> l()
<lambda>() missing 1 required positional argument: '_'

>>> l("foo")
True

So this lambda does require one argument. If you want a lambda with no argument that always returns True, do this:

>>> m = lambda: True
>>> m()
True

What does _ mean in lambda function and why is it used?

It's a convention in Python to use _ for variables that are not going to be used later. There is no black magic involved and it is an ordinary variable name that behaves exactly as you'd expect.

In this case it is used because f is passed as a callback which will be passed an argument when it is called (fxph = f(x)).

If f would have been implemented as

f = lambda: model.loss(X, y)[0]

then a TypeError: <lambda>() takes 0 positional arguments but 1 was given error will be raised.

What's the meaning of = (an arrow formed from equals & greater than) in JavaScript?

What It Is

This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences. For example, they do not bind their own values of this (see below for discussion).

Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).

You can read more in the Mozilla documentation on arrow functions.

From the Mozilla documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

A Note on How this Works in Arrow Functions

One of the most handy features of an arrow function is buried in the text above:

An arrow function... lexically binds the this value (does not bind its own this...)

What this means in simpler terms is that the arrow function retains the this value from its context and does not have its own this. A traditional function may bind its own this value, depending on how it is defined and called. This can require lots of gymnastics like self = this;, etc., to access or manipulate this from one function inside another function. For more info on this topic, see the explanation and examples in the Mozilla documentation.

Example Code

Example (also from the docs):

var a = [
"We're up all night 'til the sun",
"We're up all night to get some",
"We're up all night for good fun",
"We're up all night to get lucky"
];

// These two assignments are equivalent:

// Old-school:
var a2 = a.map(function(s){ return s.length });

// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );

// both a2 and a3 will be equal to [31, 30, 31, 31]


Notes on Compatibility

You can use arrow functions in Node, but browser support is spotty.

Browser support for this functionality has improved quite a bit, but it still is not widespread enough for most browser-based usages. As of December 12, 2017, it is supported in current versions of:

  • Chrome (v. 45+)
  • Firefox (v. 22+)
  • Edge (v. 12+)
  • Opera (v. 32+)
  • Android Browser (v. 47+)
  • Opera Mobile (v. 33+)
  • Chrome for Android (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • Samsung Internet (v. 5+)
  • Baidu Browser (v. 7.12+)

Not supported in:

  • IE (through v. 11)
  • Opera Mini (through v. 8.0)
  • Blackberry Browser (through v. 10)
  • IE Mobile (through v. 11)
  • UC Browser for Android (through v. 11.4)
  • QQ (through v. 1.2)

You can find more (and more current) information at CanIUse.com (no affiliation).



Related Topics



Leave a reply



Submit