*Asynchronous Javascript and Closure~!

Adam Dadi
2 min readFeb 21, 2021

Hello Medium!

Being that this is my first post I thought I would write about something that interests me and really had me thinking. It was a culmination of understanding and previous lessons when it clicked for me.

So far I can really see how useful and abstract React is, it is a library, not a framework which was the impression that I was under. I do like the infinite learning curve but what really intrigues me is the support and community surrounding this field. I just did a total 180-degree turn from the Real-Estate field and could not be happier with my decision.

Glad to introduce myself but let’s not digress!

I have been learning vanilla javascript and many of its concepts through trial and error. I noticed something particularly strange which led me to an aha moment. During API implementation and using Axios, it is inevitable that a promise is being used(.then() and .catch() methods). Before I continue, this blog is mainly for beginners and people that appreciate curiosity. I am well aware that I am not teaching anything new. Be nice!

Back to what’s important! I made a variable named card below the axios .get() call and that is the first instance of its creation. I then proceeded to console.log(card) above and it was undefined. Makes sense right? Sure it does, it is obeying hoisting and scope rules. However, if that is the case then why and how was my axios call able to utilize it without throwing an error?

Hmmmmmmmm…….

I felt like that was when I understood the asynchronous nature and it made total sense to me. Because of how javascript compiles info it would make sense why that console log mentioned earlier would show undefined. It made even more sense why axios was able to use it, asynchronous javascript defies this because it does not run right away. Its whole point is to not be synchronous and to be the ‘misfit’ that can not be governed by the compiling nature that's associated with javascript. I got into this by looking at my code after not seeing it for a few hours not understanding how the card variable was being used above its inception. What I want to say is that because of curiosity and the need for an explanation I figured out that Async JS holds many abilities to make sure code does not break. I implore all beginners to mess with their code and ask themselves why on everything. Do not assume, dig into it!

--

--