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]

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thx! Thats what I was stuck with... I added an equal sign after while(start <= end) so it includes the end as well.
Welcome @tyskas at SO! Do not forget to upvote and accept answer if it was useful.
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;
}

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.