0

Is n automatically set to represent array indexes starting from 0? What confuses me is that I usually set up for loops to define i as an index indicator. But here how does n do it without being set that way?

x is an array

function maps(x){
  return x.map(
    function (n) {
      return n*2
    }
  )
}

I was trying to double each element of an array. And i actually figured it out but my question is "how does it actually work?".

pilchard
  • 12,414
  • 5
  • 11
  • 23
Tamerlan
  • 3
  • 2
  • 1
    `n` is automatically set to the array elements, not the indexes. To get the indexes you need two arguments: `x.map(function(n, i) { ... })` – Barmar Apr 26 '23 at 19:42
  • 4
    [The documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is super helpful at times like these. In this case `n` is the first argument to the callback, so for each execution of the callback `n` is the array element for which it is being executed. – David Apr 26 '23 at 19:42
  • 1
    How it works: `map()` loops over the array elements (like a `for` loop might) and then calls the callback in each iteration. It collects all the results into a new array and returns it. – Barmar Apr 26 '23 at 19:44
  • 2
    @Tamerlan: You could always *test* this by creating an array, calling `.map()` on that array, and logging the value of `n` within the callback to observe it. For example: `['this', 'is', 'a', 'test'].map(function(n){ console.log(n); });` – David Apr 26 '23 at 20:01
  • 1
    Does this answer your question? [What is the concept of Array.map?](https://stackoverflow.com/questions/17367889/what-is-the-concept-of-array-map) – pilchard Apr 26 '23 at 22:18

1 Answers1

0

The function (n) { return n*2 } is accepted as an argument of a callback function by the map() method. So function (n) { return n*2 } executes for each element in the array x and its return value is added as a single element in the new array. The parameter n represents the current element being processed in the array and the second parameter should be the index of the current element being processed in the array. For example, we can turn your code snippet as the following:

let arr = [30, 51, 76];

function maps(x){ 
    return x.map( function (n, index) {
        console.log(n + " " + index);
        return n*2;
    } ) 
}

console.log(maps(arr));

Then we should get the result:

30 0
51 1
76 2
[ 60, 102, 152 ]

And we can see the indices that correspond to the elements.

I think the best way to eliminate your confusion is to figure it out how the map() method is defined. Here, I cite a piece of code snippet from https://jsvault.com/array-map to show what exactly is a map() method:

/**
 * The callback gets 3 arguments
 * the item, the index and the  execution context
 */
Array.prototype.newMap = function (callback) {
  const result = [];
  for (let index = 0; index < this.length; index++) {
    // This is primarily to check if the item
    // exists in the array, 
    if (this.indexOf(this[index]) > -1) {
      result[index] = callback(this[index], index, this)
    }
  }
  return result
}

Within the definition, there is a for loop to handle a callback function, in which case, it could be your function (n) { return n*2 }. If you want to know more details, please check the links https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and https://jsvault.com/array-map

tech-kz
  • 22
  • 4
  • The jsvault example you included is not accurate, most notably in the passing of `this` as the third argument to the callback which allows mutation of the calling array in place. Also its supposed check is faulty and doesn't skip empty indexes at all. – pilchard Apr 26 '23 at 22:13