fac24 / week3-alex-bereket-hallie-peter

https://afternoon-mesa-46889.herokuapp.com/
1 stars 1 forks source link

Don't use .map for simple loops #27

Open oliverjam opened 2 years ago

oliverjam commented 2 years ago

https://github.com/fac24/week3-alex-bereket-hallie-peter/blob/d217cd163d5b6025ba85217220e1c75404c6cef3/routes/all-posts.js#L25-L31

.map is designed to create a new array by mapping each value of the old one using the function you provide. Here you're just using it as a way to loop over the array (and then storing the result separately outside of it). Since you aren't creating a new array your code would be clearer if you just used .forEach (or a for..of loop), since those just do iteration without any extra fancy stuff.

oliverjam commented 2 years ago

Oh also be careful when trying to make copies of objects/arrays by simply assigning variables, as it won't work how you expect. For example:

const results = [1, 2]
const posts = result;
posts[0] = 999
console.log(posts); // Logs: [999, 2]
console.log(results); // Logs: [999, 2]

All the assignment does here is create a new variable that points to the exact same object (array). So line 27 effectively doesn't do anything useful; you could just get rid of it and use result directly.