Arrow Function Syntax and the ‘Return’ Keyword in JS

Feedback


Question:

Presently, I am attempting to extract the initial character from every string within the

animals

array and save it into a fresh array named

secretMessage

through the use of shorthand arrow function notation. However, an error has arisen during this process.


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(''));

What causes this issue to arise and what are the steps to rectify it?


Solution 1:

The return value is what the
arrow function
expression evaluates to.

An expression accompanied by an
implicit return
suffices for a concise body. However, for a block body, it is necessary to use an explicit

return

statement.

It is possible to eliminate the term

return

.

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


Solution 2:


Eliminate the term identified as

return

.


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

The expression is indicated by the fat arrow
function automatically returns
.

The return statement is necessary only when the function is enclosed within a block.

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


Solution 3:


If you have a one-line
Arrow Function
statement without braces, there’s no need for a return statement.


Solution 4:

Eliminate the

return

code block from the arrow function.

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

or include blocks

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

The code at Question has a problem where the output of

.map()

is not assigned to a variable. This leads to a call of

.map()

that only loops through

secretMessage

without creating a new array to hold the result. To fix this, the output of

.map()

should be assigned to a variable. Additionally, object destructuring can be used to shorten the code.

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

let secretMessage = animals.map(({0:s}) => s);

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

Frequently Asked Questions