0

I want to get an output array beginning with min value and ending with max value => [5,6,7,8,9,10].

But I get only min value in new array => [5]. Why does this happen?

function arrayFromRange(min , max){
    const newArray = [];

    for( let x = min ; x <= max; x++ ){
      newArray.push(x);
      return newArray;
    }
}
const newarray1 = arrayFromRange(5,10);

console.log(newarray1);
3
  • 1
    Because you are returning early (inside your loop rather than outside). Moev the return newArray; line outside of your loop and your function will work :) Commented Nov 16, 2022 at 9:28
  • 1
    You return inside the loop, so the first iteration the function will exit and the next iterations will never start Commented Nov 16, 2022 at 9:28
  • 2
    Does this answer your question? For loop in JS only returns first value? Commented Nov 16, 2022 at 9:30

1 Answer 1

1

You return your newArray inside the for loop, having only added the first item, in this case 5.

Solution is to move the return out of the foor loop, i.e.

function arrayFromRange(min , max){
    const newArray = [];

    for( let x = min ; x <= max; x++ ){
      newArray.push(x);
    } //                             <--swap these
    return newArray; //              <-- two lines
}
Sign up to request clarification or add additional context in comments.

Comments

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.