What is the syntax for arrow functions?

Question: in this code:

fruits.forEach(fruit => console.log(I want to eat a ${fruit}.))

Why do we drop the callback function name?

Why is it not:

fruits.forEach((function(fruit => console.log(I want to eat a ${fruit}.)))

to call as an anonymous function?

you mean the function keyword? Because the arrow functions (=>) allows us to drop the function keyword. Of course you can go for:

function(fruit){ console.log(`I want to eat a ${fruit}.`) }

but you can’t combine function keyword with arrow function. That won’t work.

1 Like

Hello guys, I’m from Brazil and it’s my first time here.

I would like to know why my code isn’t running:

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

fruits.forEach(fruit => if (fruit[0] === 'a' || fruit[0] === 'e' || fruit[0] === 'i' || fruit[0] === 'o' || fruit[0] === 'u') { 
  console.log('I want to eat an ' + fruit); } else {
	console.log('I want to eat a ' + fruit);
1 Like

it should be:

fruits.forEach(fruit => {
   /* body of the function here */

the if condition should also be in the function body

Thank you so much for helping, sir! It was really helpful.

By this point in the course one might presume we have learned about, String.includes() and, String.charAt() which will greatly simplify the above expression…


One might also presume that by this stage we have learned about ternary expressions. Since we can include a ternary expression inside console.log, we can write,

fruits.forEach(fruit => {
  console.log(`I want to eat ${`aeiou`.includes(fruit.charAt(0)) 
              ? `an` : `a`} ${fruit}.`);

I want to eat a mango.
I want to eat a papaya.
I want to eat a pineapple.
I want to eat an apple.

Granted, we don’t usually think like this on our first draft. It’s usually when we are looking for ways to refactor that stuff like this surfaces.


Why charAt()?

It returns an empty string if the index is out of range which is less likely to throw an error. It won’t raise any eyebrows in the includes() method. Were the argument to that method dynamic then as a subscript (of the string) there would be an immediate error thrown if it is out of range.