DEV Community

Discussion on: Regular vs Arrow Function

Collapse
isaacdlyman profile image
Isaac Lyman

Note that => is written with an equal sign and a greater-than sign, both common programming symbols and pretty accessibly on a standard keyboard.

As for why, the top reasons I use arrow functions are:
1) Succinctness. If I'm trying to add 1 to each element in listOfNumbers, the old way to do it was:

var incrementedNumbers = listOfNumbers.map(function (num) { return num + 1; }); 
Enter fullscreen mode Exit fullscreen mode

With an arrow function I can do

var incrementedNumbers = listOfNumbers.map(num => num + 1);
Enter fullscreen mode Exit fullscreen mode

Which is quicker to write and quicker to read.

2) Lexical context. When you write function, it creates its own this binding (that is, inside of a classic function, the this keyword refers to the function itself). But for arrow functions, this refers to the same thing both inside and outside the function; arrow functions don't create a lexical context. This is occasionally handy when I have some data in this that I need to use throughout a function, including in various predicates (like in functions passed to Array.map or async callbacks).