We are required to write an Array function (functions that lives on Array.prototype object). The function should take in a start index and an end index and it should sum all the elements from start index to end index in the array (including both start and end)
Example
const arr = [1, 2, 3, 4, 5, 6, 7]; const sumRange = function(start = 0, end = 1){ const res = []; if(start > end){ return res; }; for(let i = start; i <= end; i++){ res.push(this[i]); }; return res; }; Array.prototype.sumRange = sumRange; console.log(arr.sumRange(0, 4));
Output
And the output in the console will be −
[ 1, 2, 3, 4, 5 ]