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

Why for loop returning last value alone instead of all other values in javascript

I have function something below,

function test(){
    const obj = {}
    const arr = []

    for(let i = 0; i < 100; i++) {
        obj.i = i
        arr.push(obj)
    }

    return arr
} 

const res = test();
console.log(res);

which returns

[{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99}]

but why it not return

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

[{"i":0},{"i":1},...,{"i":99}]

any reason.

>Solution :

You are replacing the value each time it is looping.Do like this

function test(){
     const arr = []
     for(let i = 0; i < 100; i++) {
         const obj = {}
        obj.i = i
        arr.push(obj)
     }

    return arr
} 

const res = test();
console.log(res);

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