Listed below are a few things that you need to understand when you're working with JavaScript. I linked resources for some of them, for the rest, you can do a bit of searching and try to figure them out.
Call Stack & Event Loop
Event Loops Explanation
After watching this video, try out the Playground and experiment with your code!