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)
}
}
Your line
arr.push[d.urls.full]
should be
arr.push(d.urls.full)