Scope for Beginners

2 min read

In JavaScript, lexical scope deals with where your variables are defined, and how they will be accessible — or not accessible — to the rest of your code.

There are two terms to think about when talking about scope: local and global. These two terms are important to understand, because one can be more dangerous than the other when declaring variables and executing your code.

A variable is globally scoped if you declare it outside of all of your functions. For example:

When a variable is in the global scope, it can be accessed by all the code in the same JavaScript file. In this example, I’m accessing the variable a in my console.log statement, inside the myFunction function.

Local Scope

Local variables only exist inside functions. They are scoped to that individual function.
You can think of local variables as as any variables that fall between an opening and closing curly brace.
These local variables can’t be accessed by code outside of the function to which they belong.