Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda