Understanding Scope and Async/Await in JavaScript

Niani Byrd
2 min readMay 10, 2021

--

Scope can seem like a daunting concept to figure out when you’re just beginning to learn JavaScript. However, its important to fully understand how it works because it will help you manage the availability of your variables. Simply put:

“ Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.”

— Hammad Ahmed

Scope has two different types: Global and Local. We will start with global scope. Take for example the following code:

Since the variable is defined outside of the function, we still have access to the variable within the function. Let’s look at another example but with a slight variation.

We see two separate console.log outputs, but only one worked. This is because the variable assignment location was changed to within the function, thereby changing the type to a local scope. Once we attempted to console.log the output outside of the function, we encountered an error.

Async/Await and How it Works

The async/await concept of JavaScript allows your code to stop and wait until the promise is resolved. For example, async/await could be used to ensure a user is authenticated before they are allowed to access the website. Await can only be utilized when it is wrapped inside of an async function, otherwise it will not work. When making a fetch request, before we convert any responses to JSON, we must make sure we fetched the responses, which will again result in an error.

--

--

No responses yet