JavaScript Scope
A quick and easy way to see examples of Function, Block, and Global Scope within JavaScript
Table of contents
Function Scope
When you create a function, the variables can only be used within that function.
Using an anonymous function:
const dontShareVariables = () => { const x = "Not shareable" console.log(`Inside the function: ${x}`) } dontShareVariables() // Inside the function: Not shareable console.log(`Outside the function ${x}`) // x is undefined
Using a function
const dontShareVariables = () => { const x = "Not shareable" console.log(`Inside the function: ${x}`) } dontShareVariables() // Inside the function: Not shareable console.log(`Outside the function ${x}`) // x is undefined
It does not matter whether the variable was initialized with var
, let
, or const
. You cannot use the variables outside of that function because they are scoped (contained) within the function that created them.
Global Scope
Declaring variables outside of everything makes them global. They can be var
, let
, or const
and everything within that file has the ability to use them.
const x = "Im outside so Im global"
const allFunctionsCanUseGlobal = () => {
console.log(x)
}
function evenRegularFunctions() {
console.log(x)
}
allFunctionsCanUseGlobal() // "Im outside so Im global"
evenRegularFunctions() // "Im outside so Im global"
Block Scope
Blocks are defined as anything between two {}
.
This is where things can get tricky.
var x = "Global Variable with Var";
let y = "Global Variable with Let";
if (true) {
var x = "Block Scope Changed Global Var";
let y = "Block Scope Changed Global Var";
}
console.log(x); // "Block Scope Changed Global Var"
console.log(y); // "Global Variable with Let"
When you use let
to create a variable, it is contained to within the block that it was created in.