search

Home  >  Q&A  >  body text

How do higher-order functions like .map() work inside JavaScript?

<p>Nowadays everyone is trying to use these higher order functions to get promising results by writing less code. But I want to know how these functions work internally. </p> <p>Suppose I wrote something similar</p> <p> <pre class="brush:js;toolbar:false;">var numbers = [16, 25, 36]; var results = numbers.map(Math.sqrt); console.log(results); // [4, 5, 6]</pre> </p> <p>I know that each element of the "number" array is iterated one by one, but <em>how</em>? </p> <p>I tried looking for it but haven't gotten a satisfactory answer yet. </p>
P粉107772015P粉107772015461 days ago441

reply all(2)I'll reply

  • P粉505450505

    P粉5054505052023-08-26 14:30:37

    I think every supplier should follow Specifications

    A real implementation (e.g. V8) might be a bit more complex, see this answer as a start. You can also refer to the v8 source code in github, but it may not be easy to understand part of it in isolation.

    Quote from the above answer:

    ES2015 specification:

    1. Suppose O is ToObject(this value).
    2. ReturnIfAbrupt(O).
    3. Suppose len is ToLength(Get(O, "length")).
    4. ReturnIfAbrupt(len).
    5. If IsCallable(callbackfn) is false, a TypeError exception is thrown.
    6. If thisArg is provided, let T be thisArg; otherwise, let T be undefined.
    7. Suppose
    8. A is ArraySpeciesCreate(O, len).
    9. ReturnIfAbrupt(
    10. A).
    11. Let
    12. k be 0.
    13. Repeat while
    14. k < len<
        Let
      1. Pk be ToString(k).
      2. Let
      3. kPresent be HasProperty(O, Pk).
      4. ReturnIfAbrupt(
      5. kPresent).
      6. If
      7. kPresent is true, then
          Let
        1. kValue be Get(O, Pk).
        2. ReturnIfAbrupt(
        3. kValue).
        4. Let
        5. mappedValue be Call(callbackfn, T, «kValue, k >, or".
        6. ReturnIfAbrupt(
        7. mappedValue).
        8. Let
        9. State be CreateDataPropertyOrThrow(A, Pk, mappedValue).
        10. ReturnIfAbrupt(
        11. status).
      8. Increase
      9. k by 1.
    15. Return
    16. A.
    17. reply
      0
  • P粉333395496

    P粉3333954962023-08-26 09:51:45

    .map is just a method that accepts a callback, calls the callback for each item of the array, and assigns the value to the new array. It is nothing special. You can even easily implement it yourself:

    Array.prototype.myMap = function(callback) {
      const newArr = [];
      for (let i = 0; i < this.length; i++) {
        newArr.push(callback(this[i], i, this));
      }
      return newArr;
    }
    
    var numbers = [16, 25, 36];
    var results = numbers.myMap(Math.sqrt);
    console.log(results); // [4, 5, 6]

    reply
    0
  • Cancelreply