0

I am creating a function that adds the numbers within the parameters start to end to an array. I have kind of accomplished that but the function adds a few numbers beyond the end number. I have probably overcomplicated things here...

function range(start, end){

  let numbersArray = [];
 
  let counter = 0;
  
  while(counter < end){
    counter++
    
    if (counter < end){
    numbersArray.push(start++)}
 
    };
  return numbersArray
};

console.log(range(4, 11));
//[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Jamiec
  • 133,658
  • 13
  • 134
  • 193
tyskas
  • 3
  • 3

2 Answers2

0

In your case at counter the beginning must be equal start. Because of that there is no need in variable counter, can use start:

function range(start , end){
  let numbersArray = [];
  while(start <= end){ 
    numbersArray.push( start );
    start += 1;
  };

  return numbersArray
};

But while can lead to eternal loop, so better use this answer

Mehan Alavi
  • 278
  • 3
  • 17
zswqa
  • 826
  • 5
  • 15
  • Thx! Thats what I was stuck with... I added an equal sign after while(start <= end) so it includes the end as well. – tyskas Jul 22 '21 at 09:21
  • Welcome @tyskas at SO! Do not forget to upvote and accept answer if it was useful. – zswqa Jul 22 '21 at 09:26
0

Is this what you want? https://jsfiddle.net/bagnk3z4/2/

function range(start, end) {
    let array = [];
    while (start <= end) {
        array.push(start++);
    }
    return array;
}
Jesper
  • 1,007
  • 7
  • 24
  • Heyy... thx for the input. The jsfiddle link stuff I havent learned yet but I am sure it works as well. Taking my baby steps :) – tyskas Jul 22 '21 at 09:38