JavaScript variable scope
determining the "jurisdiction" of a variable
Depending on where it gets declared, a variable "exists" (i.e. is accessible) only within its scope, which varies based on which set of brackets it "resides" in:
global scope variable
a variable that we can access (use or call) from anywhere
usually outside of a function at the beginning of a script file
often declared using the keyword
var
before the variable namea variable with
let
could still have a global scope
block scope variable
a variable that we can access inside the set of curly braces ("the block") we declare it in
declared using either
const
orlet
in ES6
trying to access this variable outside of the block will result in an error
local scope variable
a variable that we can access inside a function and only inside that function
declared also using
const
orlet
in ES6
Last updated