Click on text below to jump to specific point in the video


In this series we are learning how to do functional programming in JavaScript. We learnt about filter last episode. In this episode, we will learn about map - which is another higher order function like filter. Also like filter, it goes through an array, but unlike filter it does not throw the objects away, it transforms them.
Start demo
We want to get an array of all the names of all the animals.
Doing it with a for loop


Let us do it with map instead.
Remember that map is a function on the array object. It takes a callback function. The callback function will be passed each item in the animals array. Here is where it differs from filter - filter expects the callback function to return a true or false value - map will include all items in the array but instead expect the callback function to return a transformed object that it will put into the new array instead of the original item. In this case that will be the name.
Using a map to return a subset of the object is a very common usage.
However, since map just expects the callback to return any object we can use it to create completely new objects.
Example of creating new object with map
We need to use much less code.Which almost always means less bugs.
In ECMAScript 6, we are getting arrow functions.

Rewrite code using arrow function
If your function logic fits in one line, you can also get rid of the return statement and the curly brackets.

Arrow functions are part of ECMAScript 6 standard.
You can use the harmony_arrow_functions flag. You can go even shorter and shorten the variable name to x.
Video outline created using VideoJots