Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implement polyfill for Array.prototype.reduce() method in JavaScript
The polyfill is a concept to extend the browser's features using user-defined methods. If the user's browser is not updated, it can happen that browser doesn't support the newer features of any programming language, such as JavaScript.
As a developer, we require to check whether the feature is supported by the browser, and if not, we need to invoke a user-defined method.
In this tutorial, we will discuss implementing the polyfill for the array.reduce() method. If any browser doesn't support the array.reduce() method, we will invoke the user-defined reduce() method.
Before we start with the tutorial, let's understand what reduce() method does. The reduce() method reduces the array into a single element. For example, we can use the array.reduce() method to find the sum of all elements in the array as we reduce all array elements into the single sum variable. Also, we can use the reduce() method to concat all strings of the array into a single string.
Syntax
Users can follow the syntax below to implement the polyfill for the array.reduce() method.
Array.prototype.reduce = function (callbackFunc, initial) {
// implement logic for reduce() method
}
In the above syntax, we have added the reduce() method to the prototype object of the Array object. We need to implement the logic of reduce() method inside the function.
Example (Using the built-in reduce() method)
In the example below, we created the array of numbers and used the reduce() method to get a sum of all array elements. Users can observe how we have reduced the array into a single element.
<html>
<body>
<h2>Using the reduce() method without polyfill in JavaScript</h2>
<div id="content"></div>
<script>
let content = document.getElementById('content');
function callback(sum, value) {
return sum + value;
}
let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
let sum = array.reduce(callback, 0);
content.innerHTML += "The array values are " + array + "<br>";
content.innerHTML += "The sum of all array elements using the array.reduce() method is " + sum + "<br>";
</script>
</body>
</html>
The array values are 30,50,6,7,8,9,50,3,2,3,43,5,4,3,23,32,456 The sum of all array elements using the array.reduce() method is 590
Implementing the polyfill for reduce() method
Users should follow the below steps to implement the logic of the array.reduce() method.
Step 1 - Create a singleElement variable and initialize it with the initial value passed as an argument. Also, the initial is an optional parameter, so it can be undefined if users haven't passed the initial value as an argument of the reduce() method.
Step 2 - Use the for loop to iterate through the array.
Step 3 - If the value of singleElement is undefined, initialize it with the first element of the array.
Step 4 - Use the call() method to execute the callback function for every array element and replace the value of the singleElement variable with returned value from the callback function.
Step 5 - Once the iteration of for loop completes, return the singleElement variable's value.
Example
In the example below, we are doing the sum of the array elements using the reduce() method as in the above example, but here we are using the user-defined reduce() method.
We have followed the above steps to implement the user-defined reduce() method, and users can observe that it gives the same output as previous example.
<html>
<body>
<h2>Using the reduce() method with polyfill in JavaScript</h2>
<div id="content"></div>
<script>
let content = document.getElementById('content');
// Define our polyfill
Array.prototype.reduce = function (callbackFunc, initial) {
let singleElement = initial;
for (let k = 0; k < this.length; k++) {
if (singleElement !== undefined) {
singleElement = callbackFunc.call(null, singleElement, this[k], k, this);
} else {
singleElement = this[k];
}
}
return singleElement;
}
function callback(sum, value) {
return sum + value;
}
let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
let sum = array.reduce(callback, 0);
content.innerHTML += "The array values are " + array + "<br>";
content.innerHTML += "The sum of all array elements using the polyfilled reduce() method is " + sum + "<br>";
</script>
</body>
</html>
The array values are 30,50,6,7,8,9,50,3,2,3,43,5,4,3,23, 32,456 The sum of all array elements using the polyfilled reduce() method is 590
Optimized Polyfill Example
We have optimized the polyfilled reduce() method in the example below. We have used the forEach() method inside the reduce() method to improve iteration performance. Also, we have used the ternary operator to initialize the start variable.
Furthermore, we have defined the array of strings and converted all array elements into a single string using the array.reduce() method.
<html>
<body>
<h2>Using optimized reduce() polyfill in JavaScript</h2>
<div id="content"></div>
<script>
let content = document.getElementById('content');
// Optimized polyfill
Array.prototype.reduce = function (callbackFunc, start) {
let array = this;
array.forEach(value => {
start = start !== undefined ? callbackFunc(start, value) : value;
});
return start;
}
function callback(finalStr, str) {
return finalStr + str;
}
let strings = [" Hi ", " Users ", "!", " Welcome ", " to ", " the ", " TutorialsPoint's ", " JavaScript ", " blog! "];
let finalStr = strings.reduce(callback, "");
content.innerHTML += "The array values: " + strings + "<br>";
content.innerHTML += "The final string after merging all array values: " + finalStr + "<br>";
</script>
</body>
</html>
The array values: Hi , Users ,!, Welcome , to , the , TutorialsPoint's , JavaScript , blog! The final string after merging all array values: Hi Users ! Welcome to the TutorialsPoint's JavaScript blog!
Complete Polyfill Implementation
Here's a more robust polyfill that handles edge cases:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback, initialValue) {
if (this == null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
let array = Object(this);
let len = parseInt(array.length) || 0;
let k = 0;
let value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in array)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = array[k++];
}
while (k < len) {
if (k in array) {
value = callback(value, array[k], k, array);
}
k++;
}
return value;
};
}
Conclusion
We learned to implement the polyfill for the array.reduce() method using two different approaches. The polyfill ensures backward compatibility by providing reduce() functionality in browsers that don't support it natively. Use the complete implementation for production code as it handles edge cases properly.
