Exercise 4.1
The Sum of a Range
My first function
var array =[];
function range1(start,end){
for(var i = start; i <= end; i =i+1)
array.push(i);
return array;
}
function range2(start,end,step){
if(step == null) step = 1;
var array=[];
if(step >0){
for(var i = start; i<= end; i+=step)
array.push(i);
}else{
for(var i = start; i>= end; i += step)
array.push(i);
}
return array;
}
function sum(array){
var num = 0
for(var i = 0; i <= array.length-1; i=i+1)
num = array[i] + num;
return num ;
}
console.log(range1(1, 10))
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range2(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range2(1, 10)));
// → 55
To open the JavaScript console, press F12 or on MAC press COMMAND-OPTION-I.