Higher Order Function: Range and Sum

I am asked to do the following:

  • Write a range function that takes 3 arguments: start, end and step. Return an array containing all the numbers from start to end.

  • Step indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one.

  • Write a sum function that takes an array of numbers and returns the sum of these numbers.

  • Below is my code, I think I have tackled the sum function portion, the range function portion is not working out:

   //Range Function Portion

    function range(start, end, step) {
    var arr = [];
    if (step>0) {
      for(var i = start; i <= end; i=i + step){
    }else {
      for(var i = end; i <= start; i++){
    return arr;

    //Sum Function Portion

    function sum(arr) {
    var sum = 0;
    // Write code here
    for(var i = 0; i < arr.length; i++) {
    sum += arr[i];
    return sum;

//I am supposed to output the following:

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


the loop in your else statement - which is the one executing here - will not works because the setting up is considering to always have a start higher than end.

with this it is again the loop in your else working, here you have the end lower than start but you still start from the lowest number, when you should start from the highest, so you get [2, 3, 4, 5] instead of [5, 4, 3, 2]