DEV Community

Cover image for Modern JavaScript: Preparation for React Dev (part 2)
raddevus
raddevus

Posted on

Modern JavaScript: Preparation for React Dev (part 2)

Continuing examination of JavaScript concepts that will be needed as we begin to learn React. Part 1 of this article.

The inspiration for these items comes from chapter to of the fantastic book, Learning React (O'Reilly publishers) by Alex Banks & Eve Porcello

Array Method : Map

Keep the following in mind as we begin to delve in to some functional aspects of JavaScript.

Arrays in JavaScript have a method named map().

Keep the following details about he map() method in mind:

  • accepts one parameter which is function that returns a single value or object
  • the map() method returns an array of items
  • When you call map() on the array (passing in your function) it will call the function once for each element in the array that it is running on.
let allItems = ['a','b','c'];
// fakeFunc will run 3 times, once for each element in allItems
allItems.map(fakeFunc);  
Enter fullscreen mode Exit fullscreen mode
  • Whatever value your function returns will be added to the final array that is returned by map().
  • It is possible for your passed in function to take 0 to many parameters, but it may only return on value (or object). Very often your method will take one parameter.

Long Version of map() : No Arrow Function

First, let's take a look at the long version of the map() function, where we use a function definition (aka declaration) instead of an arrow* function.

*We'll go over arrow functions in part 3 of this article series. After we look at the longer method they will make more sense.

let allItems = ['a','b','c'];
function convertToByte(inChar){
   return inChar.charCodeAt(inChar);
}
allItems.map(convertToByte);
Enter fullscreen mode Exit fullscreen mode

If you copy/paste and run that code in your Web Dev console (F12 in most browsers) you will see that an array is returned with the charCode values for each character.

The last line in the following snapshot is the array that is returned from map().

Alt Text

Add Emoji Character

Just for fun, let's try it again with an emoji character in the array so you can see the value.

NOTE: I named the allItems array as allItems2, just so I wouldn't get an error message about allItems being redeclared.

Alt Text

This map() method is very cool because if we did this with imperative code (we write the algorithm) instead of the functional declarative way, we would have to write a for loop to do the work to iterate over each item in the array.
map() does all that work for us. Very cool.

Arrow Function Makes It Cleaner

We can make it a bit cleaner with an arrow function though.

We will delve into arrow functions in part 3 of this series. See you next time.

Latest comments (0)