DEV Community

Cover image for Understanding Scope Chain
codethepotato
codethepotato

Posted on

Understanding Scope Chain

Today we are going to discuss Scope Chain. This was something I struggled to understand. The stress of trying to keep up in class while figuring out what this meant was too much to handle.
Scope, in JavaScript, determines the accessibility of variables and functions at various parts in one's code/program. When inside a scope of a variable, function, or method data can be accessed.
There are three types of scopes available:

  1. Global Scope
  2. Function Scope
  3. Block Scope

Global Scope

When a variable is declared outside of a function it becomes Global. Meaning all variables can be accessed from anywhere in a program.

let petName = 'Keebs';
//code here can use petName

function newFunction() {
//code here can also use petName 
}
Enter fullscreen mode Exit fullscreen mode

Function Scope

Variables defined inside of a function are not accessible from outside the function. Quite similar as using let, var and/or const inside of the function.

function petFunction() {
let petName = 'Keebs';  //example of Function Scope
}
Enter fullscreen mode Exit fullscreen mode

Back in 2015, JavaScript only had Global Scope and Function Scope. Then when ES6 was introduced they provided the very important keywords: let and const. Only these two keywords provide Block Scope!

Block Scope

Variables declared inside curly brackets {} can NOT be accessed from outside the block.

{
  let x = 10;
}
// x can NOT be accessed here!
Enter fullscreen mode Exit fullscreen mode

When declaring variables with var, they do NOT have block scope! Even declared inside of a {} block, they can be accessed from outside the block.

{
var x = 10
}
// x CAN be accessed here!
Enter fullscreen mode Exit fullscreen mode

It is so important to watch where you are declaring your variables, compared to where they are going to be needed. Knowing the Scope Chain will help immeasurably as your coding starts to come more naturally. This will allow you get to farther with less errors.

I hope that this blog has helped you understand Scope Chain a little more and pushes you along this knowledge path we are both adventuring!

Good luck and don't give up!! :)

Top comments (0)