Home > Net >  I want to get array using given min , max range
I want to get array using given min , max range

Time:11-16

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

CodePudding user response:

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
}
  • Related