What is the scope of variables in JavaScript?
TLDR
JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code.
The four scopes are:
- Global - visible by everything
- Function - visible within a function (and its sub-functions and blocks)
- Block - visible within a block (and its sub-blocks)
- Module - visible within a module
Outside of the special cases of global and module scope, variables are declared using var
(function scope), let
(block scope), and const
(block scope). Most other forms of identifier declaration have block scope in strict mode.
Overview
Scope is the region of the codebase over which an identifier is valid.
A lexical environment is a mapping between identifier names and the values associated with them.
Scope is formed of a linked nesting of lexical environments, with each level in the nesting corresponding to a lexical environment of an ancestor execution context.
These linked lexical environments form a scope "chain". Identifier resolution is the process of searching along this chain for a matching identifier.
Identifier resolution only occurs in one direction: outwards. In this way, outer lexical environments cannot "see" into inner lexical environments.
There are three pertinent factors in deciding the scope of an identifier in JavaScript:
- How an identifier was declared
- Where an identifier was declared
- Whether you are in strict mode or non-strict mode
Some of the ways identifiers can be declared:
var
,let
andconst
- Function parameters
- Catch block parameter
- Function declarations
- Named function expressions
- Implicitly defined properties on the global object (i.e., missing out
var
in non-strict mode) import
statementseval
Some of the locations identifiers can be declared:
- Global context
- Function body
- Ordinary block
- The top of a control structure (e.g., loop, if, while, etc.)
- Control structure body
- Modules
Declaration Styles
var
Identifiers declared using var
have function scope, apart from when they are declared directly in the global context, in which case they are added as properties on the global object and have global scope. There are separate rules for their use in eval
functions.
let and const
Identifiers declared using let
and const
have block scope, apart from when they are declared directly in the global context, in which case they have global scope.
Note: let
, const
and var
are all hoisted. This means that their logical position of definition is the top of their enclosing scope (block or function). However, variables declared using let
and const
cannot be read or assigned to until control has passed the point of declaration in the source code. The interim period is known as the temporal dead zone.
function f() {
function g() {
console.log(x)
}
let x = 1
g()
}
f() // 1 because x is hoisted even though declared with `let`!
What is scope default of a variable defined by JavaScript var?
Based on this source
Scope of the variables declared without var keyword become global irrespective of where it is declared. Global variables can be accessed from anywhere in the web page. Visit Scope for more information.
Javascript for-loop variable scope?
Before ECMAScript 6, javascript only supports function scoping. A variable declared inside a function is visible anywhere inside that function. Even this:
function foo() { if(true) { if(true) { var v = 7; } }
console.log(v); // 7}foo();
Variables with the same name, but the local scope variable isn't being used, why?
You have declared a variable named a
three times.
- Once as a global on line 1:
var a = 15;
- Twice inside the function:
- Once with a
var
statement on line 4:var a;
- Once with an argument definition on line 3:
function checkScope(a) {
- Once with a
The line 4 var
has no effect. The variable is already declared.
Then you call checkScope(a);
which passes the value of the global a
(15) to the local a
argument of checkScope
. This is why it is 15
and not undefined
.
Since they're re-declared, If I'm interpreting MDN correctly, does that mean line 3 is basically ignored?
var a
is basically ignored.
But I don't think so because both variable are declared in their own, separate execution contexts
This is where you are being tripped up by having three and not two declarations of a
. It declares the variable defined by the function argument name.
Javascript: scope of variable
The let
keyword gives a variable block-level scope, meaning the v1
variable in b()
is only usable inside b()
. a()
does not know what v1
is.
//// does not work
function a() {
console.log(v1);
}
function b() {
let v1 = 1;
a();
}
b();
In this example, v1
is being set in the global scope, so all your functions will recognize it.
//// does work
function a() {
console.log(v1);
}
function b() {
a();
}
let v1 = 1;
b();
What is file scope in javascript
ES6 modules form their own file scope (as if the entire contents of the file were wrapped in a function).
Variables declared in a module are completely inaccessible from outside that module (unless they're export
ed).
Related Topics
Modifying CSS Class Property Values on the Fly With JavaScript/Jquery
How to Add Multiple Classes to a Reactjs Component
Which Equals Operator (== VS ===) Should Be Used in JavaScript Comparisons
Var Functionname = Function() {} VS Function Functionname() {}
How to Reload CSS Without Reloading the Page
Use a Content Script to Access the Page Context Variables and Functions
How to Redirect to Another Webpage
How to Replace All Occurrences of a String in JavaScript
How to Copy to the Clipboard in JavaScript
Why Is Document.Write Considered a "Bad Practice"
Inject CSS Stylesheet as String Using JavaScript
JavaScript: Find Div'S Line-Height, Not CSS Property But Actual Line-Height
Dynamically Access Object Property Using Variable
Using Async/Await With a Foreach Loop
How to Avoid the Need For Ctrl-Click in a Multi-Select Box Using JavaScript
How to Convert Base64 String to JavaScript File Object Like as from File Input Form