DEV Community

Cover image for Returning object literals using Javascript arrow function
Jyotirmoy Das
Jyotirmoy Das

Posted on • Updated on

Returning object literals using Javascript arrow function

Now this is one such problem where I found myself stuck for 30 odd minutes only because I didn't knew the usage of arrow functions properly. It's common for developers to feel "Ya i know that thing...", but when we encounter a problem where the logic you implemented seems all correct but there's some error with the syntax. So here I am going to discuss about a problem where I had to map one array of objects to another. The problem goes like -

You have an array of user objects, each one has name, surname and id. Write the code to create another array from it, of objects with id and fullName, where fullName is generated from name and surname.

Normally it's an easy problem (for any developer who has done some programming). This was my first attempt -


let john = { name: "John", surname: "Smith", id: 1 };
let pete = { name: "Pete", surname: "Hunt", id: 2 };
let mary = { name: "Mary", surname: "Key", id: 3 };
let users = [ john, pete, mary ];
let usersMapped = users.map(item=>{
fullName:
${item.name} ${item.surname},
id: item.id,
});
console.log(usersMapped);

This was okay for me as far as the logic of the problem was concerned. But on running, it gave me a bunch of errors. After proper research on the subject I found out that I was not using the arrow function properly. I found out that while using arrow functions with object literals we have to wrap the object literals with parenthesis. Although I had learned the arrow function and done quite a few problems using the same, I was not aware of this fact that led me to this error and this wonderful insight.

The fix : (see there's an extra pair of parentheses added)

let usersMapped = users.map(item=>({
fullName:
${item.name} ${item.surname},
id: item.id,
}));

In short : If you have to return objects using arrow function, wrap the object literals in parentheses.

References :
https://javascript.info/task/map-objects
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

NOTE :
This article does not claim to provide the best method of using arrow functions. There might be plenty more elegant methods of implementing the same. Through this article I am just sharing one of my experiences while solving a problem and how I started to learn from the errors. Also I would love to improve if you let me know my mistakes on this article.

Top comments (0)