-3

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 counting by step.

It seems very simple, however my code, is incorrect:

const range = function(start, end, step) {
  for (let i = start; i <= end; i += step);
  return (start, end, step);
}

console.log(range(0, 10, 2));  

Why is my code incorrect?

Thank you.

billygreen
  • 223
  • 3
  • 12
  • "console.log only prints 2" - no, it does not. Your function doesn't return anything. – ASDFGerte Aug 10 '18 at 00:09
  • There is no array generated anywhere in your code. You just have a `for` loop that does nothing but increment `i`. – Sebastian Simon Aug 10 '18 at 00:09
  • I had a return (start, end, step); in there as well, which returned a 2. How do I fix the function overall? – billygreen Aug 10 '18 at 00:14
  • 1
    Use an array, not the comma operator. Voting to close as typo – CertainPerformance Aug 10 '18 at 00:16
  • 1
    `return (start, end, step);` is equivalent to `return step;`. See [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). See the documentation for [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). – Sebastian Simon Aug 10 '18 at 00:17

2 Answers2

2

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));
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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]
gavgrif
  • 15,194
  • 2
  • 25
  • 27