What is the difference between global, function, and block scope?
Quick answer
Scope is the part of a program where a variable name can be accessed. Global scope is the surrounding top-level scope; function scope confines a name to its function; block scope confines it to a block such as an if statement. var is scoped to its containing function or top-level scope, not an ordinary nested block. let and const are limited to their block. [S1] [S2]
The question, the details, the next step.
A practical checklist
Find the declaration keyword:
var,let, orconst.Mark the containing function’s opening and closing braces.
Mark smaller block braces, such as those around an
ifstatement.For
var, check whether a reference remains within its containing function or top-level scope. [S1]For
letandconst, check whether a reference remains inside the block where each was declared. [S2]Test questionable references separately so one error does not stop the rest of an example.
A few more useful answers
Does `var` become block-scoped when it is inside an `if` statement?
No. var does not acquire ordinary block scope; it is scoped to its containing function or the relevant top-level scope. [S1]
Are `let` and `const` scoped to the whole function?
Not necessarily. They are limited to the block where they are declared, which can be a smaller block inside a function. [S2]
Does a top-level declaration always work across separate JavaScript modules?
These scope rules do not establish that a module-level name is automatically available in other modules. The description of var includes module scope. [S1]
Sources
References used for this guide.
- [S1] var — JavaScript | MDN developer.mozilla.org · Checked
- [S2] Block statement — JavaScript | MDN developer.mozilla.org · Checked
