Don t use arrow functions... (if you don t need to)

Eckehard - Jul 21 '23 - - Dev Community

We can love them or hate them, but arrow functions often allow to write more compact code. Sometimes there are good reasons to use them, if you need to deal with "this" in your code. But often, they tend to be harder to read.

So, when or when not should you use arrow functions?

We can write Javascript functions multiple ways:

hello = function() { // conventional function
  return "Hello World!"
}
const hello = () => { // "arrow"-function
  return "Hello World!"
}
// arrow-function with implicit return
const hello = () => "Hello World!" 
Enter fullscreen mode Exit fullscreen mode

Especially the last version has some nice options to shorten expressions, if you combine arrow functions with the ternary operator:

// conventional function
function getcolor(flag) 
{
    if (flag)
        return = "green"
    else
        return = "red"
}

// Arrow-function
const getcolor = (flag) => flag ? "green" : "red"
Enter fullscreen mode Exit fullscreen mode

even the brackets () around (flag) are not necessary, but it is a good convention to place them to mark the (argument) of the arrow function. Here we possibly get the best from using Arrow functions. Code is shorter and pretty clear. But: be carful not to exaggerate this!

const decode = c => 
   (Array.isArray(c)) ? c.map(el => (el>0 ? el : -el)) : (c > 0 ? c : -c)
Enter fullscreen mode Exit fullscreen mode

This is working code, but what does it do? Hard to say... I often spent hours just to figure out, what a single line of code does. This is pure waste of time!

Keep it clear and simple

I want to encourage you to write readable code! Computer just do what the code tells them to do, but programmers are responsible to maintain the code. Writing readable code will save you time and make your live easier.

Are arrow functions really more compact?

For short functions, that simply return a value, the arrow syntax provides an option, to write more compact code. But the next example shows, that arrows => are not always shorter:

  function f(a,b) { ... }
  const f = (a,b) => { ... }  
Enter fullscreen mode Exit fullscreen mode

The function operator shows immediately: Here we define a function. This is not alwas and immediately clear with the arrow operator, specially if you use deeply nested functions inside.

Even if it saves some bytes, for the sake of readability, you should prefer the good old "function()" where possible!


Remember: One day of debugging can save you 5 seconds of writing more readable code...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .