samsos samsos - 24 days ago 8
Javascript Question

JS: Using 'return' in arrow function syntax

I'm currently trying to return every first character of each string in the

animals
array and storing in a new array called
secretMessage
using shorthand arrow function syntax. But, I run into the following error.

Error

/home/ccuser/workspace/learn-javascript-iterators-E3/main.js:5
secretMessage.map(animal => return animal[0]);
^^^^^^
SyntaxError: Unexpected token return


Js

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

secretMessage.map(animal => return animal[0]);

console.log(secretMessage.join(''));


Why does this occur? and how can resolve this error?

Answer Source

The expression in an arrow function is the value for return.

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

You could just remove the word return.

var secretMessage = animals.map(animal => animal[0]);