CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

πŸ”„ Array.prototype.reduce() Polyfill

The reduce() method executes a reducer function on array elements to produce a single value. Powerful for aggregations and transformations.

The method executes a reducer function on each element of the array, resulting in a single output value. This polyfill is spec-compliant, handling edge cases like sparse arrays, missing initial values, and proper validation. -- βœ… Spec-Compliant Implementation -- βœ… How to Use -- 🎯 Output Example Calling: Logs: -- <!-quiz-start --Q1: What happens when calling without an initial value? [ ] Returns undefined [ ] Returns 0 [x] Throws a TypeError [ ] Returns an empty array Q2: When no initial value is provided, what does use as the initial accumulator? [ ] undefined [ ] 0 [ ] The last element of the array [x] The first defined element of the array Q3: How does handle sparse arrays (arrays with holes)? [ ] Treats holes as undefined [x] Skips holes and only processes existing elements [ ] Throws an error when encountering holes [ ] Fills holes with null before processing <!-quiz-end --
JavaScriptPolyfills
🎯 Array.prototype.at() Polyfill
medium
βœ… Array.prototype.every() Polyfill
medium
πŸ”² Array.prototype.fill() Polyfill
medium
πŸ” Array.prototype.filter() Polyfill
medium
πŸ”Ž Array.prototype.find() Polyfill
medium
πŸ”’ Array.prototype.findIndex() Polyfill
medium
πŸ”™ Array.prototype.findLast() Polyfill
medium
πŸ”™ Array.prototype.findLastIndex() Polyfill
medium
πŸ“‹ Array.prototype.flat() Polyfill
medium
πŸ” Array.prototype.includes() Polyfill
medium
πŸ”’ Array.prototype.indexOf() Polyfill
medium
βœ… Array.isArray() Polyfill
medium
πŸ—ΊοΈ Array.prototype.map() Polyfill
hard
βž– Array.prototype.pop() Polyfill
medium
βž• Array.prototype.push() Polyfill
easy
πŸ”„ Array.prototype.reduce() Polyfill
medium
πŸ”„ Array.prototype.reverse() Polyfill
hard
⬅️ Array.prototype.shift() Polyfill
hard
πŸ”˜ Array.prototype.some() Polyfill
medium
πŸ”€ Array.prototype.sort() Polyfill
hard
➑️ Array.prototype.unshift() Polyfill
hard
πŸ“ž Function.prototype.apply() Polyfill
medium
πŸ”— Function.prototype.bind() Polyfill
hard
πŸ“ž Function.prototype.call() Polyfill
medium
16 of 24
LibraryJavaScriptPolyfills31 of 61

πŸ”„ Array.prototype.reduce() Polyfill

jspolyfillsmedium

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. This polyfill is spec-compliant, handling edge cases like sparse arrays, missing initial values, and proper validation.


βœ… Spec-Compliant Implementation

if (!Array.prototype.reduce) {
  Array.prototype.reduce = function(callback, initialValue) {
    console.log('πŸ”§ AOT 1: Validate `this`');
    if (this == null) throw new TypeError('Called on null or undefined');

    console.log('πŸ”§ AOT 2: Validate callback');
    if (typeof callback !== 'function') throw new TypeError('Callback is not a function');

    console.log('πŸ”§ AOT 3: Normalize input');
    const array = Object(this);
    const length = array.length >>> 0;
    console.log('Array:', array);
    console.log('Length:', length);

    let index = 0;
    let accumulator;

    if (arguments.length >= 2) {
      console.log('πŸ”§ AOT 4: Using provided initialValue:', initialValue);
      accumulator = initialValue;
    } else {
      console.log('πŸ”§ AOT 5: No initialValue, searching for first defined element...');
      while (index < length && !(index in array)) {
        console.log(` - Skipping hole at index ${index}`);
        index++;
      }
      if (index >= length) {
        console.log('❌ AOT ERROR: No elements to use as initial accumulator');
        throw new TypeError('Reduce of empty array with no initial value');
      }
      accumulator = array[index];
      console.log(`βœ… Found initial value at index ${index}:`, accumulator);
      index++;
    }

    console.log('πŸ”§ AOT 6: Begin reduction loop');
    for (; index < length; index++) {
      if (index in array) {
        console.log(`β†ͺ️  Applying callback at index ${index}:`, {
          accumulator,
          currentValue: array[index],
        });
        accumulator = callback(accumulator, array[index], index, array);
        console.log('    -> New accumulator:', accumulator);
      } else {
        console.log(` - Skipping hole at index ${index}`);
      }
    }

    console.log('βœ… AOT 7: Returning final result:', accumulator);
    return accumulator;
  };
}

βœ… How to Use

[1, 2, 3, 4].reduce((a, b) => a + b);         // Normal reduce
[1, 2, 3, 4].reduce((a, b) => a + b, 10);     // With initial value
[,,3].reduce((a, b) => a + b, 1);             // Sparse array with initial
[].reduce((a, b) => a + b);                   // ❌ Error

🎯 Output Example

Calling:

[1, 2, 3].reduce((a, b) => a + b);

Logs:

πŸ”§ AOT 1: Validate `this`
πŸ”§ AOT 2: Validate callback
πŸ”§ AOT 3: Normalize input
Array: [1, 2, 3]
Length: 3
πŸ”§ AOT 5: No initialValue, searching for first defined element...
βœ… Found initial value at index 0: 1
πŸ”§ AOT 6: Begin reduction loop
β†ͺ️  Applying callback at index 1: { accumulator: 1, currentValue: 2 }
    -> New accumulator: 3
β†ͺ️  Applying callback at index 2: { accumulator: 3, currentValue: 3 }
    -> New accumulator: 6
βœ… AOT 7: Returning final result: 6

Quick Quiz

Test your understanding with 3 quick questions

Q1What happens when calling `[].reduce((a, b) => a + b)` without an initial value?
Q2When no initial value is provided, what does `reduce()` use as the initial accumulator?
Q3How does `reduce()` handle sparse arrays (arrays with holes)?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna