Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
Javascript array.push does not seem to work in a for loop

I have come across very strange behavior in nodeJS. I am trying to initialize an empty array and then fill that array inside a for loop. See the simplified code below.

let arr = []
for (let i = 0; i < 20; i++) {
    console.log(arr)
    arr.push(`hello`)
}
console.log(arr)

This outputs just an empty array at every instance of the loop and afterwards.

[]
[]
[]
[]
...
[]

I can't for the life of me figure out why that is. I assume it has something to do with scoping but the array is still accessible inside the loop when I do a straight assignment to it. Any help would be greatly appreciated!

Edit: Here is the full code that I am struggling with. The arr.push does not seem to push the new urls into the arr. Thank you

const getRandImgs = async (ct) => {
    console.log('At the top of getRandImgs')
    try {
        let arr = []
        if (ct > 30) {
            arr = await getRandImgs(30)
            console.log(arr)
            ct -= 30
        }

        const config = {
            params: {
                collections: '483251',
                count: ct
            },
            headers: {
                Authorization: 'Client-ID XXXXXXX'
            }
        }
        const res = await axios.get('https://api.unsplash.com/photos/random', config)

        for (const d of res.data) {
            console.log(d.urls.full)
            console.log(arr)
            arr.push[d.urls.full]
            console.log(arr)
        }
        return arr
    } catch (e) {
        console.log(e)
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your line

arr.push[d.urls.full]

should be

arr.push(d.urls.full)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!