React Tutorial history map (step, move)

Viewed 2472

In the "Showing the Past Moves" section here, we have the below code:

const moves = history.map((step, move) => {
      const desc = move ?
        'Go to move #' + move :
        'Go to game start';
      return (
        <li>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

This code seems to be first mapping a built in variable "step" to variable "move", before essentially having this Python logic:

const moves = [lambda move: const desc = move ... for move in history]

As someone who is familiar with Python but not javascript, can you explain:

1) "step" variable is not assigned anywhere, and I haven't been able to google a built in step variable, so how is "step" getting assigned to the number of game moves?

2) What is the logic behind this syntax: (step, move) meaning first map step into move, then execute a lambda function? Primarily, the first 'map step into move' part doesn't make sense to me.

2 Answers

The JavaScript Array map() function has the following syntax:

array.map(function(currentValue, index, arr), thisValue)

In this case, the step variable is the value of the current element of the history array being iterated by the map function. The move variable is the index of the current element.

Typically you use the map function to return a new array based upon the original array. In this case, they are iterating the history of moves and creating a new array of HTML <btn> elements based upon the history.

You could accomplish the same using forEach like so:

let moves = [];
history.forEach((step, move) => {
    const desc = move ?
          'Go to move #' + move :
          'Go to game start';
    moves.push(
        <li>
            <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
    );
});

map is a function available on arrays. It is used to map all elements in the array to something else. For example, if you wanted to double all the elements in an array, you would:

const arr = [1, 2, 3, 4];
const newArr = arr.map(element => element * 2)
console.log(newArr);

It is equivalent to

const arr = [1, 2, 3, 4];
const newArr = [];

for (var i = 0; i < arr.length; i++) {
  newArr.push(arr[i] * 2);
}

console.log(newArr);

In your case, history is an array. And you're mapping every step (just every element of history) to an li React element. There is no concept of 'map step into move' here. Also, move is just the index of the step in your array.

Related