I am trying to define a function range which takes 3 integer parameters: start, end, and step.
The function should return an array of numbers from start to end count
Your for
loop isn't doing anything. In particular, it's not creating an array. You're just trying to return the 3 inputs, not the array of numbers that's supposed to be generated. But since you're combining them with the comma operator, you just return the last parameter (see What does a comma do in JavaScript expressions?).
Your loop needs a body that adds the current element to an array.
const range = function(start, end, step) {
const result = []
for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
}
console.log(range(0, 10, 2));
Create an array and use your existing for loop to push the values to that array andthen return the array. I have given both a for loop and a while loop that gets the job done.
// using a for loop
const range = function(start, end, step) {
let arr = [];
for (i = start; i <= end; i += step){
arr.push(i);
};
return arr;
}
console.log("Using a for loop: ", range(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]
// using a while loop
const range2 = function(start, end, step) {
let arr = [];
let i = start
while (i <= end){
arr.push(i);
i += step;
};
return arr;
}
console.log("Using a while loop: ", range2(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]