Hi im doing the first part of eloquent javascript chp4 The Sum of a Range. After spending some time i was sure i cracked the first part.
"Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end."
I have looked at peoples answers but they all include the further parts of the question. I want to keep it simple, after all if i cant do the first part then there's no hope. it seems easy.
function range(start, end) {
let array = [];
for (let i = start; i <= end; i++){array.push(i);}
}
console.log(range(20 , 25));
but i get undefined, i have tried even copying and reducing the books answers to a similar situation.
It feels like my brain just cant do code. Where am i going wrong? Why is it undefined?
below is given answer
function range(start, end, step = start < end ? 1 : -1) {
let array = [];
if (step > 0) {
for (let i = start; i <= end; i += step) array.push(i);
} else {
for (let i = start; i >= end; i += step) array.push(i);
}
return array;
}
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
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
thx guys
returning thearrayat the end of yourrangefunction, resulting in calls torangealways returningundefined.return arrayjust before closing your loop