DEV Community

spencer-w-mathews
spencer-w-mathews

Posted on

Understanding Scope In JavaScript

What is scope in JavaScript?
Every variable within JavaScript has a scope. The scope of the variable governs the variables accessibility. The accessibility of the variable is where you are able to access the variable within the JavaScript you are working with.

Different types of scope
Global Scope
Global scope occurs when a variable is accessible from anywhere within the file. When a variable is declared outside of any function the variable will be accessible globally.
The three ways to declare a variable (var, let, const) will all act the same when declared globally.

let name = "foo"
//name variable can be accessed
function whatsName(){
//name variable can be accessed
}

Function Scope
Functions all have Function Scope. Function scope means variables declared within a function are accessible only within the function. Just as with Global Scope the three ways to declare a variable (var, let, const) will all act the same when declared globally.

function functionScope() {
let = "variable"; // Function Scope
}

Block Scope
Block Scope denies access to variables declared within an {} block from outside. This wasn't established until 2015. Block Scope is only possible with const and let. Var allows variables to be accessed from outside the {} block.

{
let variable = 2;
}
// variable can not be accessed here
{
var variable = 2;
}
// variable can be accessed here

Why do you need to understand scope?
Understanding the scope of each variable declared within a JavaScript file lets the author of the code to be more agile and accurate. Scope can cause headaches and hang-ups. Not having a solid understanding of scope costs time. Hopefully, this blog post adds to your understanding of Scope.

source(s): W3 Schools

Top comments (0)