惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
SecWiki News
SecWiki News
N
News | PayPal Newsroom
T
Tor Project blog
W
WeLiveSecurity
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
月光博客
月光博客
AWS News Blog
AWS News Blog
D
Docker
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
I
InfoQ
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
S
Security Affairs
WordPress大学
WordPress大学
T
Threatpost
Microsoft Security Blog
Microsoft Security Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
B
Blog RSS Feed
Project Zero
Project Zero
P
Proofpoint News Feed

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
A Simple Explanation of Scope in JavaScript
Dmitri Pavlutin · 2020-04-20 · via Dmitri Pavlutin Blog

The scope is an important concept that manages the availability of variables. The scope is at the base closures, defines the idea of global and local variables.

If you'd like to code in JavaScript, understanding the scope of variables is a must.

In this post, I will explain step by step, in-depth, how the scope works in JavaScript.

Table of Contents

  • 1. The scope
  • 2. Block scope
    • 2.1 var is not block scoped
  • 3. Function scope
  • 4. Module scope
  • 5. Scopes can be nested
  • 6. Global scope
  • 7. Lexical scope
  • 8. Variables isolation
  • 9. Conclusion

1. The scope

Before diving into what the scope is, let's try an experiment that demonstrates how the scope manifests itself.

Let's say you define a variable message:


const message = 'Hello';

console.log(message); // 'Hello'


Then, you could easily log this variable in the next line after the declaration. No questions here.

Now, let's move the declaration of message inside of an if code block:


if (true) {

const message = 'Hello';

}

console.log(message); // ReferenceError: message is not defined


This time, when trying to log the variable, JavaScript throws ReferenceError: message is not defined.

Why does it happen?

The if code block creates a scope for message variable. And message variable can be accessed only within this scope.

JavaScript Scope

At a higher level, the accessibility of variables is limited by the scope where they're created. You are free to access the variable defined within its scope. But outside of its scope, the variable is inaccessible.

Now, let's put down a general definition of scope:

The scope is a policy that manages the accessibility of variables.

2. Block scope

A code block in JavaScript defines a scope for variables declared using let and const:


if (true) {

// "if" block scope

const message = 'Hello';

console.log(message); // 'Hello'

}

console.log(message); // throws ReferenceError


The first console.log(message) correctly logs the variable because message is accessed from the scope where it is defined.

But the second console.log(message) throws a reference error because message variable is accessed outside of its scope: the variable doesn't exist here.

The code block of if, for, while statements also create a scope.

In the following example for loop defines a scope:


for (const color of ['green', 'red', 'blue']) {

// "for" block scope

const message = 'Hi';

console.log(color); // 'green', 'red', 'blue'

console.log(message); // 'Hi', 'Hi', 'Hi'

}

console.log(color); // throws ReferenceError

console.log(message); // throws ReferenceError


color and message variables exist within the scope of while code block.

Same way the code block of while statement creates a scope for its variables:


while (/* condition */) {

// "while" block scope

const message = 'Hi';

console.log(message); // 'Hi'

}

console.log(message); // => throws ReferenceError


message is defined within while() body, consequently message is accessible only within while() body.

In JavaScript you can define standalone code blocks. The standalone code blocks also delimit a scope:


{

// block scope

const message = 'Hello';

console.log(message); // 'Hello'

}

console.log(message); // throws ReferenceError


2.1 var is not block scoped

As seen in the previous section, the code block creates a scope for variables declared using const and let. However, that's not the case of variables declared using var.

The snippet below declares a variable count using a var statement:


if (true) {

// "if" block scope

var count = 0;

console.log(count); // 0

}

console.log(count); // 0


count variable, as expected, is accessible within the scope of if code block. However, count variable is also accessible outside!

A code block does not create a scope for var variables, but a function body does. Read the previous sentence again, and try to remember it.

Let's continue on the function scope in the next section.

3. Function scope

A function in JavaScript defines a scope for variables declared using var, let and const.

Let's declare a var variable within a function body:


function run() {

// "run" function scope

var message = 'Run, Forrest, Run!';

console.log(message); // 'Run, Forrest, Run!'

}

run();

console.log(message); // throws ReferenceError


run() function body creates a scope. The variable message is accessible inside of the function scope, but inaccessible outside.

Same way, a function body creates a scope for let, const and even function declarations.


function run() {

// "run" function scope

const two = 2;

let count = 0;

function run2() {}

console.log(two); // 2

console.log(count); // 0

console.log(run2); // function

}

run();

console.log(two); // throws ReferenceError

console.log(count); // throws ReferenceError

console.log(run2); // throws ReferenceError


4. Module scope

ES2015 module also creates a scope for variables, functions, classes.

The module circle defines a constant pi (for some internal usage):


// "circle" module scope

const pi = 3.14159;

console.log(pi); // 3.14159

// Usage of pi


pi variable is declared within the scope of circle module. Also, the variable pi is not exported from the module.

Then the circle module is imported:


import './circle';

console.log(pi); // throws ReferenceError


The variable pi is not accessible outside of circle module (unless explicitly exported using export).

The module scope makes the module encapsulated. Every private variable (that's not exported) remains an internal detail of the module, and the module scope protects these variables from being accessed outside.

Looking from another angle, the scope is an encapsulation mechanism for code blocks, functions, and modules.

5. Scopes can be nested

An interesting property of scopes is that they can be nested.

In the following example the function run() creates a scope, and inside an if condition code block creates another scope:


function run() {

// "run" function scope

const message = 'Run, Forrest, Run!';

if (true) {

// "if" code block scope

const friend = 'Bubba';

console.log(message); // 'Run, Forrest, Run!'

}

console.log(friend); // throws ReferenceError

}

run();


if code block scope is nested inside the run() function scope. Scopes of any type (code block, function, module) can be nested.

The scope contained within another scope is named inner scope. In the example, if code block scope is an inner scope of run() function scope.

The scope that wraps another scope is named outer scope. In the example, run() function scope is an outer scope to if code block scope.

JavaScript Nested Scopes

What about the variable's accessibility? Here's one simple rule to remember:

The inner scope can access the variables of its outer scope.

message variable, which is a part of the run() function scope (outer scope), is accessible inside if code block scope (inner scope).

6. Global scope

The global scope is the outermost scope. It is accessible from any inner (aka local) scope.

In a browser environment, the topmost scope of JavaScript file loaded using <script> tag is a global scope:


<script src="myScript.js"></script>



// myScript.js

// "global" scope

let counter = 1;


A variable declared inside the global scope is named global variable. Global variables are accessible from any scope.

In the previous code snippet, counter is a global variable. This variable can be accessed from any place of the webpage's JavaScript.

The global scope is a mechanism that lets the host of JavaScript (browser, Node) supply applications with host-specific functions as global variables.

window and document, for example, are global variables supplied by the browser. In a Node environment, you can access process object as a global variable.

7. Lexical scope

Let's define 2 functions, having the function innerFunc() is nested inside outerFunc().


function outerFunc() {

// the outer scope

let outerVar = 'I am from outside!';

function innerFunc() {

// the inner scope

console.log(outerVar); // 'I am from outside!'

}

return innerFunc;

}

const inner = outerFunc();

inner();


Look at the last line of the snippet inner(): the innerFunc() invokation happens outside of outerFunc() scope. Still, how does JavaScript understand that outerVar inside innerFunc() corresponds to the variable outerVar of outerFunc()?

The answer is due to lexical scoping.

JavaScript implements a scoping mechanism named lexical scoping (or static scoping). Lexical scoping means that the accessibility of variables is determined statically by the position of the variables within the nested function scopes: the inner function scope can access variables from the outer function scope.

A formal definition of lexical scope:

The lexical scope consists of outer scopes determined statically.

In the example, the lexical scope of innerFunc() consists of the scope of outerFunc().

Moreover, the innerFunc() is a closure because it captures the variable outerVar from the lexical scope.

If you'd like to master the closure concept, I highly recommend reading my post A Simple Explanation of JavaScript Closures.

8. Variables isolation

An immediate property of scope arises: the scope isolates the variables. And what's good different scopes can have variables with the same name.

You can reuse common variables names (count, index, current, value, etc) in different scopes without collisions.

foo() and bar() function scopes have their own, but same named, variables count:


function foo() {

// "foo" function scope

let count = 0;

console.log(count); // 0

}

function bar() {

// "bar" function scope

let count = 1;

console.log(count); // 1

}

foo();

bar();


9. Conclusion

The scope is a policy that manages the availability of variables. A variable defined inside a scope is accessible only within that scope, but inaccessible outside.

In JavaScript, scopes are created by code blocks, functions, modules.

While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules.

Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.

The lexical scope consists of the outer function scopes determined statically. Any function, no matter the place where being executed, can access the variables of its lexical scope (this is the concept of closure).

Hopefully, my post has helped you understand the scope better!