Using _ (Underscore) Variable with Arrow Functions in Es6/Typescript

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.

Difference between ()= and _= and (_)= in JS ES6

The general form of a fat-arrow function is

(parameter-list) => function-body

If you don't have any parameters, you use a pair of empty parentheses:

() => {}

If you have a single parameter it's:

(x) => {}

Since _ is a valid identifier in JavaScript, you can do:

(_) => {}

Now, a special rule applies: If you have only one parameter, you can skip the parentheses, so you get:

_ => {}

Please note that this is only valid if you have a single parameter, i.e. for two you always have to specify the parentheses:

(x, y) => {}

Now, on the right side, if your entire function only consists of a single statement with a return, such as

x => { return x; }

you can omit the curly braces and the return:

x => x

At least, this is true if on the right side you don't try to return an object, which would look like this (this code won't work!):

x => { value: x }

The reason why this does not work is that JavaScript can not distinguish this from a function body, which also uses curly braces, so now you have to wrap it in parentheses:

x => ({ value: x })

I think that's pretty much everything you need to know about the syntax of fat arrow functions.

What is the Underscore for in front of the arrow function (_=) in the hero.service.ts Angular v5 Tour of Heroes Tutorial?

Its nothing but a notion to name a parameter which isn't going to be used in the function.

Instead, they would have written it like this:

tap(() => this.log(`updated hero id=${hero.id}`)),

If you want to read more, this post is a good start.

What is the meaning of an Underscore in javascript function parameter?

The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter.

A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter". Since JavaScript doesn't do parameter-count checking the parameter could have been omitted entirely.

This symbol is often used (by convention again) in conjunction with fat-arrow functions to make them even terser and readable, like this:

const fun = _ => console.log('Hello, World!')
fun()

In this case, the function needs no params to run, so the developer has used the underscore as a convention to indicate this. The same thing could be written like this:

const fun = () => console.log('Hello, World!')
fun()

The difference is that the second version is a function with no parameters, but the first version has a parameter called _ that is ignored. These are different though and the second version is safer, if slightly more verbose (1 extra character).

Also, consider a case like

arr.forEach(function (_, i) {..})

Where _ indicates the first parameter is not to be used.

The use of underscores like this can get very confusing when using the popular lodash or underscore libraries.

Function without argument : () or _

() is a list of zero parameters.

(_) is a list of one parameter (named _)

_ is a shorthand for (_) because the parentheses are optional when there is exactly one parameter.


"Wrong" is subjective, but:

  • if a function doesn't use any parameters then providing a variable to assign them to doesn't make sense (not even if it has a name which tells you nothing about what it is for).
  • writing non-idiomatic code imposes barriers for people who have to come along and maintain your code later.

Aside: You have a syntax error. You can't combine the function keyword with an arrow function.

Angular tutorial Tour of Hero, what does _ means in the following code

_ is in this case just a blank identifier used to shorten the arrow function. So in this case

_ => this.log(`updated hero id=${hero.id}`)

would be equivalent to

() => this.log(`updated hero id=${hero.id}`)

With the minor difference that _ would be accessible as an argument within the arrow function (although it will likely have the value undefined), whereas the second snippet won't have any accessible arguments.

Finally, variables starting with _ (or just _ itself) have a special property in typescript. Such variables do not cause a compilation error when they are not used while the --noUnusedParameters flag is set.

In ES6, can I use Arrow functions as short hand for .bind(this, ...) with arguments?

The problem I essentially was trying to solve was the classic "use setTimeout to call a function with parameters" problem, except with arrow functions. (But more generally, with any function, not just setTimeout.)

There are three nearly identical ways to solve this (the last one with arrow functions):

Using closures

var self = this;
functionThatReturnsAPromise()
.then((function() { return self.someFunction(obj.a + obj.b); }));

It works, but I would explicitly have to set this to some other variable, like self.

Using bind

functionThatReturnsAPromise()
.then((function(a, b) { return this.someFunction(a + b); }).bind(this, obj.a, obj.b));

A little better than the first, since I can just use this without any hackery, but it gets quite a bit verbose.

Using ES6 arrow functions

functionThatReturnsAPromise()
.then(() => this.someFunction(obj.a + obj.b));

A ha! Very concise. I no longer have to specify this, and I don't have to pass in any parameters either, since the arrow function preserves the parent closures stack frame. When the arrow function gets executed, it knows what obj.a and obj.b refer to. I have now achieved bind functionality with ES6 arrow function syntax.



Related Topics



Leave a reply



Submit