Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Reduce Pollyfill

I was playing around with this array reduce polyfill and I'm just confused why is he/she using apply. I know that apply adds this context in the execution. But I don't know why we need it here, I just tried without it, and it works fine too.

Array.prototype.reduce = function (cb, initialValue) {
  console.log('inside my reducer');
  if (!cb || typeof cb !== 'function') throw TypeError();
  var len = this.length;
  var i = 0;
  console.log('this', this);
  if (typeof initialValue === 'undefined' || initialValue === null) {
    initialValue = this[0];
    ++i;
  }

  for (; i < len; i++) {
    initialValue = cb.apply(this, [initialValue, this[i], i, this]);

    //comment the line above and uncomment this line and it will work fine
    //initialValue = cb(initialValue, this[i]); 
    
  }

  return initialValue;
};
[1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5

So, I'm a little confused, if anyone could share some insights it'll be apreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Wherever you got that polyfill, it's incorrect, in a couple of ways but in particular that initialValue = cb.apply(this, [initialValue, this[i], i, this]); should be using undefined, not this, in the first argument. reduce always calls its callback with this set to undefined (it'll end up being the global object if the callback is in loose mode rather than strict mode). So either initialValue = cb.apply(undefined, [initialValue, this[i], i, this]); or (more directly) initialValue = cb(initialValue, this[i], i, this);

Separately, it makes no sense to use apply and create an array to provide to it rather than using call with the discrete values it already has. Also, continuing to use something called initialValue for the accumulator is, at best, misleading. And it doesn't handle it correctly if you do [].reduce(x => x) (it should throw an error, not return undefined [note no seed value]).

So basically, I wouldn't put much faith in that polyfill, since it's providing the array, rather than undefined, as this during callbacks.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!