Scoping in JavaScript refers to what variables your program has access to at any given moment in time. So let’s start scooping into this scope stuff…

What are the different types of scopes?

  • Global scope
  • Function scope
  • Block scope

By default, when coding in JavaScript, you start in the window scope or the root scope. This is the global scope. This means there is only one global scope in a JS document.

Global Variables

Declaring a variable outside of a function is creating a global variable. Global variables have a global scope. Variables in the global scope can be accessed anywhere else in your program, in any other scope.

Local Variables

Unlike global variables, local variables are only available inside an enclosed part of your programs such as a function or block scope, like if statements or loops. A local variable has a local scope…

Image for post

If you run this code, the global variable globalVar can be accessed inside the function localScope. However, the local variable localVar can only be accessed in the scope of the function localScope and not in the global scope.

You can think of local scopes as a diary. Pretend you are a child keeping a diary (a local scope). You can write whatever you want inside of your diary (i.e. create as many variables as you want in a function), and name events that took place outside of your diary (accessing global variables outside of your function or calling other functions). However, no one else can look inside your diary, ESPECIALLY not your parents…cough…cough…GLOBAL SCOPES. Similar to how a parent is not able to look inside a child’s diary, you are not able to access local variables in the global scope.

#js #programming #javascript #coding #fundamentals

The Scoop on Scope (In JavaScript)
1.55 GEEK