Make a better code and best practices

Make a better code and best practices
0.0 0

#1

Hi every body !
Today i do the challenge “ES6: Create Strings using Template Literals” and i asked myself a question. How i can make a cleaner, readable and maintainable code ? For this challenge i found two possibility, maybe and i think there are more solutions, but i my case what’s a best practices ? In generally it’s better to use a loop (for of) or use a function ?

If you have some documents of this subject, please link us. :wink:

Thanks for reading this post.
Faithfully yours.


#2

It depends Richard,

I suggest the for loop. It’s more compatible. Because I’m not a JS expert, but almost every developer(including me) could understand a simple for loop, but not lambda, arrow function, and more lang specific(mostly modern) stuffs.

This could be viceversa too! If you work with a group of JS devs, they probably go for map version I believe and finds the for loop kind of so old, retro, and meh.

The answer is easy, if X version is great and easy for you, your group and people code your lang, then go for it, otherwise go for Y version.

Keep going on great work, happy programming.


#3

arr.map is the cleanest solution. No extraneous variables, no imperative iteration. No wondering if any other part of your code is also pushing to resultDisplayArray.

It may seem obvious that you aren’t mistakenly pushing to the array, until a bug pops up and shows you actually are.

But this comes down to preference really. Both of the ways you wrote it are readable and maintainable.

Also, you don’t need to do slice() before calling map. The map method already returns a new array – it clones it under the hood for you.

// this is all you need
arr
   .map(/*...*/)

And you don’t need to create an IIFE. Just assign the result to a variable. When the js engine reaches that line in the code, it will automatically evaluate the expression and assign the result to the variable.

// not this
const resultDisplayArray = (() => /*...*/))()

// this is all you need
const resultDisplayArray = arr.map(/*...*/)

Lastly, when you use an arrow function that returns a single expression, you don’t need curly braces.

const resultDisplayArray = () => arr.map(/*...*/)

Keep up the great work.


#4

@NULL_dev & @JM-Mendez thank you for your answers!
I’ll follow your advice!
Indeed arr.map(//) seem better. :smile: