Can't access element in array

Hey, I’ve been scratching my head over this for a while, lots of trial and error and searching but no solution yet. I’m doing the random quote generator challenge, and trying to use the quotesondesign API.

Please have a look at my js code here: https://codepen.io/GreatScot/pen/jmQQMR

I created a getQuote() function, which uses the callback function in jQuery’s getJSON() method to push some data into an array, and return that array. If you follow my console.log calls, you can see that the array is populated with the results from the API call, but for some reason when I try to access one of the elements by index, I just get “undefined” (and typeof also returns undefined).

Have tried a few things, but am not getting anywhere with it. Anyone see where I am going wrong?

Thanks.

see this example if it helps you https://codepen.io/abdellah-el-mennani/pen/YVoWMP?editors=1111

the problem you do is you try to access the variable before the get initialized by the value returned from the requests to the the database

for example in the function that fetch the quotes you will always get undefined because you return the value of the quote varible even before the getting the response for the db. read again how the asynchronous programming in js works.

and sorry for my english

1 Like