My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Best practices: variable assignment within built-in methods [JavaScript]

Natasha's photo
Natasha
·Aug 23, 2017

Let's say you have the following code:

const groceryList = ['apple', 'orange', 'celery', 'pineapple'];
let fiber;
const modifiedList = groceryList.map(item => {
if (item !== 'celery') {return `${item} juice`;}

fiber = item;
});
// modifiedList = ['apple juice','orange juice','pineapple juice'];
// fiber = 'celery'

[other code that consumes these variables]

I want to avoid iterating through the entire list again just to handle one case, but this solution seems less than ideal. I'm wonder if there's an industry standard or if this is considered a bad practice?