JSMonday 01 – The awesome .map method
source link: https://www.tuicool.com/articles/hit/IR773mb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Let’s say you have an array of N numbers and you want to multiply each number by 2.
Bad Practice
- This way, you will mutate your original array. You won’t be able to access your original array again.
- It’s hard to read. Loops are efficient but really hard to read due to their imperative nature.
- Hard to maintain. Loops themselves are hard to maintain. Nested loops and conditions inside of them are hell.
Better practice
This way you will get a new array without compromising the original one. It is still difficult to read and maintain.
Best practice
The Array.map
method will solve you a lot of problem.
The code will become declarative , describing your resulting data and how you will get it.
You can read the code above as:
“ newArray
is a list of number, where each number the product of the multiplication by 2 of every number contained in arr
”.
Try to do the same with the previous example, it won’t be easy!
It will be easier to maintain thanks to its declarative nature, fastest to write and to explain.
Anatomy of the .map method
.map
method can be used against any kind of array (array of strings, integers, undefined values and so on).
It will accept a function
as argument, where you’ll have access to every single array element and its corresponding index.
See the examples below:
You can always add any kind of expression inside your map
body:
But remember to return
a value. Otherwise, you’re gonna get the following result:
See you next week with a new episode of Js Monday !
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK