6

I have either a typescript or javascript syntax issue. Can someone tell me what _ => this.log... means?

I am used to seeing a name the parameter being passed into the arrow function there.

Does it simply mean 'no parameter'?

Ref: https://angular.io/tutorial/toh-pt6#add-heroserviceupdatehero

    /** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
  return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
    tap(_ => this.log(`updated hero id=${hero.id}`)),
    catchError(this.handleError<any>('updateHero'))
  );
}
31piy
  • 23,323
  • 6
  • 47
  • 67
OpTech Marketing
  • 417
  • 2
  • 6
  • 19
  • Possible duplicate of [Using \_ (underscore) variable with arrow functions in ES6/Typescript](https://stackoverflow.com/questions/41085189/using-underscore-variable-with-arrow-functions-in-es6-typescript) – Carolus Jul 25 '19 at 14:33

2 Answers2

13

() => {console.log('Hello World')}

  _ => {console.log('Hello World')}

Both of the above are just the same if your function doesn't need a parameter.

The underscore _ is just a throwaway variable, meaning it can be any variable name since it will never be used. It's just that they usually use the underscore to say that the function doesn't need a parameter.

I write my functions with no parameters using ()=>, but I've seen a lot of versions using the underscore so it's good to understand both.

Carolus
  • 477
  • 4
  • 16
dev mamba
  • 676
  • 7
  • 10
9

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.

31piy
  • 23,323
  • 6
  • 47
  • 67