Click on text below to jump to specific point in the video
Start demoWe 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 mapWe need to use much less code.Which almost always means less bugs.
In ECMAScript 6, we are getting arrow functions.
Rewrite code using arrow functionIf 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