Explain the difference between global scope, function scope, and block scope
Topics
JavaScript
Edit on GitHub
TL;DR
Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within {}
) they are declared in.
Global scope, function scope, and block scope
Global scope
Variables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the window
object.
Function scope
Variables declared within a function are only accessible within that function. This is true for variables declared using var
, let
, or const
.
Block scope
Variables declared with let
or const
within a block (e.g., within {}
) are only accessible within that block. This is not true for var
, which is function-scoped.