Question about syntax used for the "The .findIndex() Method" questions

Hi. I was wondering why the correct solutions are all written in the syntax including “return”. The code can be written more succinctly (and as far as I can tell, cleaner and more readable) if I omit “return”. Eg. for the two exercises about .findIndex() I didn’t get these solutions approved (although the answers seemed correct when I logged to console):

const foundAnimal = animals.findIndex(animal => animal === ‘elephant’)
const startsWith = 1 + animals.findIndex(animal => animal[0] === ‘s’)

Why does the course favor the seemingly more awkward “return” syntax? I.e.: what are the gains from using it that balance out the loss of succinctness/ readability?

That is not a question we can answer without being in the author’s head. A callback function is nothing new.

animals.findIndex(function (animal) {
    return animal === 'elephant'

Of course when the new streamlined lambda syntax was introduced everyone was excited to put it to good use. Only thing is, its best use case is in simple callbacks like this, but it took a while for folks to catch on so we would see a lot of this:

animals.findIndex((animal) => {
    return animal === 'elephant'

In that sense it hardly seems worthwhile bringing in the new syntax given the old vanilla code is not much improved. But, when we put concise body arrow functions to good use, we get,

animals.findIndex(x => x === 'elephant')

Fits like a glove. No parens on the parameter; no curly braces; implicit return. Done like dinner.

As for using the syntax in more complex functions it is rather pointless but you will see how some people ‘like’ to use arrow functions better than ES5 vanilla functions. This is subjective and has no basis in reasoning.

1 Like