Sum of all numbers in a range! (spoiler Alert)

Hey I have my solution, it works fine and all. But I want to understand how the Math.max and min functions work.

Solution:


function sumAll(arr) {
  var min = Math.min.apply(null, arr);
  var max = Math.max.apply(null, arr);
  var results = 0;
  
//   if(arr[0] < arr[1]){
//     min = arr[0];
//     max = arr[1];
//   }else{
//     min = arr[1];
//     max = arr[0];
//   }
  
  while(min <= max){
    results += min;
    min += 1; 
  }
  
  return results;
}

sumAll([1, 4]);

Why do I need to include a “null” in my math.max callback for it to return the largest number in a given array???

Math.max() takes numbers as arguments, and returns the largest of them. For instance,

Math.max(1, 2, 3) // 3
Math.max(1, 8, 15, 30, 2) // 30

However, if you want to get the maximum of a number in an array, you want to pass the numbers that are in the array to the max function, not the array itself. That’s where the apply function comes in to play.

apply() is a function that every function in javascript has. In this case, here’s what’s happening:

var arr = [1, 2, 3];
Math.max(1, 2, 3) === Math.max.apply(null, arr);

The apply() function takes two arguments: the first is the this argument: that is, the value that will be passed to the function as this. The second argument that apply() takes is an array of arguments to pass to the function that we’re calling, in this case Math.max.

I don’t know how well I’ve explained this, so if you’re looking for more information, take a look at the MDN page for apply().