
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Accumulating some value over using a callback function and initial value in JavaScript
Problem
We are required to write a JavaScript function that takes in an array a callback function and an initial value.
The function should accumulate a value over the iteration of array and finally return the value just like the Array.prototype.reduce() does.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5]; const sum = (a, b) => a + b; Array.prototype.customReduce = function(callback, initial){ if(!initial){ initial = this[0]; }; let res = initial; for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){ res = callback(res, this[i]); }; return res; }; console.log(arr.customReduce(sum, 0));
Output
Following is the console output −
15
- Related Articles
- Passing a function as a callback in JavaScript
- Calculating value of a sequence based on some input using JavaScript
- Callback function in C
- Sorting an array that contains the value of some weights using JavaScript
- How to set initial value and auto increment in MySQL?
- How to return a value from a JavaScript function?
- Initial Value Theorem of Laplace Transform
- Initial Value Theorem of Z-Transform
- Function to create diamond shape given a value in JavaScript?
- Set auto increment initial value for MySQL table using ALTER command
- Setting a default variable value to undefined in a function - JavaScript?
- How to convert a pixel value to a number value using JavaScript?
- Create a vertical slider with custom min, max, and initial value in Java
- How to change the value of a global variable inside of a function using JavaScript?
- divisibleBy() function over array in JavaScript

Advertisements