As a newbie to front-end development, I am trying to understand why developers would want to use arrow functions. It seems to me that it would just be easier to type the word function and return than to type an arrow function, unless they create a arrow function key on keyboards.
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:
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).
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
As a newbie to front-end development, I am trying to understand why developers would want to use arrow functions. It seems to me that it would just be easier to type the word function and return than to type an arrow function, unless they create a arrow function key on keyboards.
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:With an arrow function I can do
Which is quicker to write and quicker to read.
2) Lexical context. When you write
function
, it creates its ownthis
binding (that is, inside of a classic function, thethis
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 inthis
that I need to use throughout a function, including in various predicates (like in functions passed toArray.map
or async callbacks).