40

JSMonday 01 – The awesome .map method

 5 years ago
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.
bqmi6vZ.png!web6jIRVj3.png!web

Let’s say you have an array of N numbers and you want to multiply each number by 2.

Bad Practice

jiiyyab.jpg!web
  1. This way, you will mutate your original array. You won’t be able to access your original array again.
  2. It’s hard to read. Loops are efficient but really hard to read due to their imperative nature.
  3. Hard to maintain. Loops themselves are hard to maintain. Nested loops and conditions inside of them are hell.

Better practice

jiiyyab.jpg!web

This way you will get a new array without compromising the original one. It is still difficult to read and maintain.

Best practice

jiiyyab.jpg!web

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

yARbMzJ.png!webbuMFbqY.png!web

.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:

jiiyyab.jpg!web

You can always add any kind of expression inside your map body:

jiiyyab.jpg!web

But remember to return a value. Otherwise, you’re gonna get the following result:

jiiyyab.jpg!web

See you next week with a new episode of Js Monday !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK