Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to get array using given min , max range

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading