snazzybouche snazzybouche - 5 months ago 14
Javascript Question

Converting ECMAScript 6's arrow function to a regular function

I have the following arrow function

if( rowCheckStatuses.reduce((a, b) => a + b, 0) ){}


rowCheckStatuses
is an array of 1's and 0's, this arrow function adds them all up to produce a number. This number acts as a boolean to determine whether or not there is at least one "1" in the array.

The issue is, I don't really understand how arrow functions work, and my IDE thinks it's bad syntax and refuses to check the rest of my document for syntax errors.

How would I go about converting this to a regular function to alleviate both issues?

Thank you very much!

Answer

You can refactor it as:

if( rowCheckStatuses.reduce(function(a, b){return a + b}, 0)

The initial accumulator isn't necessary (unless you expect the array to be empty sometimes), it could be:

if( rowCheckStatuses.reduce(function(a, b){return a + b})

This number acts as a boolean to determine whether or not there is at least one "1" in the array

It might be faster (and clearer) to use:

if( rowCheckStatuses.some(function(a){return a == 1}))

which will return true if there are any 1s in rowCheckStatuses and will return as soon as one is encountered. Another alternative is indexOf:

if( rowCheckStatuses.indexOf(1) != -1)

Lots of alternatives.

Comments