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

推荐订阅源

Vercel News
Vercel News
T
Tor Project blog
博客园_首页
F
Fortinet All Blogs
V
V2EX
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
博客园 - 【当耐特】
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
Engineering at Meta
Engineering at Meta
Spread Privacy
Spread Privacy
C
Cyber Attacks, Cyber Crime and Cyber Security
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Apple Machine Learning Research
Apple Machine Learning Research
V2EX - 技术
V2EX - 技术
Latest news
Latest news
L
LINUX DO - 最新话题
IT之家
IT之家
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 叶小钗
博客园 - Franky
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
博客园 - 聂微东
MyScale Blog
MyScale Blog
S
Security @ Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
小众软件
小众软件
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Vulnerabilities – Threatpost
T
Tailwind CSS Blog
L
Lohrmann on Cybersecurity
T
Troy Hunt's Blog
美团技术团队

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()
JavaScript Closure: The Beginner's Friendly Guide
Dmitri Pavlutin · 2019-10-25 · via Dmitri Pavlutin Blog

The callbacks, event handlers, higher-order functions can access outer scope variables thanks to the closure. The closure concept is important in functional programming and is often asked during the JavaScript coding interview.

While being used everywhere, closures are difficult to grasp. If you haven't had your "Aha!" moment in understanding closures, then this post is for you.

I'll start with the fundamental terms: scope and lexical scope. Then, after grasping the basics, you'll need just one step to finally understand closures.

Before starting, I suggest you resist the urge to skip the scope and lexical scope sections. These concepts are crucial to closures, and if you get them well, the idea of closure becomes self-evident.

1. The scope

When you define a variable, you want it to exist within some boundaries. E.g. a result variable makes sense to exist within a calculate() function, as an internal detail. Outside of the calculate(), the result variable is useless.

The accessibility of variables is managed by scope. You are free to access the variable defined within its scope. But outside of that scope, the variable is inaccessible.

In JavaScript, a scope is created by a function or a code block.

Let's see how the scope affects the availability of a variable count. This variable belongs to the scope created by function foo():


function foo() {

// The function scope

let count = 0;

console.log(count); // logs 0

}

foo();

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


Open the demo.

count is freely accessed within the scope of foo().

However, outside of the foo() scope, count is inaccessible. If you try to access count from outside anyways, JavaScript throws ReferenceError: count is not defined.

If you've defined a variable inside of a function or code block, then you can use this variable only within that function or code block. The above example demonstrates this behavior.

The JavaScript scope

Now, let's see a general formulation:

The scope is a space policy that rules the accessibility of variables.

An immediate property arises — the scope isolates variables. That's great because 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); // logs 0

}

function bar() {

// "bar" function scope

let count = 1;

console.log(count); // logs 1

}

foo();

bar();


Open the demo.

count variables from foo() and bar() function scopes do not collide.

2. Scopes nesting

Let's play a bit more with scopes, and nest one scope into another. For example, the function innerFunc() is nested inside an outer function outerFunc().

How would the 2 function scopes interact with each other? Can I access the variable outerVar of outerFunc() from within innerFunc() scope?

Let's try that in the example:


function outerFunc() {

// the outer scope

let outerVar = 'I am outside!';

function innerFunc() {

// the inner scope

console.log(outerVar); // => logs "I am outside!"

}

innerFunc();

}

outerFunc();


Open the demo.

Indeed, outerVar variable is accessible inside innerFunc() scope. The variables of the outer scope are accessible inside the inner scope.

The JavaScript scopes can be nested

Now you know 2 interesting things:

  • Scopes can be nested
  • The variables of the outer scope are accessible inside the inner scope

3. The lexical scope

How does JavaScript understand that outerVar inside innerFunc() corresponds to the variable outerVar of outerFunc()?

JavaScript implements a scoping mechanism named lexical scoping (or static scoping). Lexical scoping means that the accessibility of variables is determined by the position of the variables inside the nested scopes.

Simpler, the lexical scoping means that inside the inner scope you can access variables of outer scopes.

It's called lexical (or static) because the engine determines (at lexing time) the nesting of scopes just by looking at the JavaScript source code, without executing it.

The distilled idea of the lexical scope:

The lexical scope consists of outer scopes determined statically.

For example:


const myGlobal = 0;

function func() {

const myVar = 1;

console.log(myGlobal); // logs "0"

function innerOfFunc() {

const myInnerVar = 2;

console.log(myVar, myGlobal); // logs "1 0"

function innerOfInnerOfFunc() {

console.log(myInnerVar, myVar, myGlobal); // logs "2 1 0"

}

innerOfInnerOfFunc();

}

innerOfFunc();

}

func();


Open the demo.

The lexical scope of innerOfInnerOfFunc() consits of scopes of innerOfFunc(), func() and global scope (the outermost scope). Within innerOfInnerOfFunc() you can access the lexical scope variables myInnerVar, myVar and myGlobal.

The lexical scope of innerFunc() consists of func() and global scope. Within innerOfFunc() you can access the lexical scope variables myVar and myGlobal.

Finally, the lexical scope of func() consists of only the global scope. Within func() you can access the lexical scope variable myGlobal.

4. The closure

Ok, the lexical scope allows to access the variables statically of the outer scopes. There's just one step until the closure!

Let's take a look again at the outerFunc() and innerFunc() example:


function outerFunc() {

let outerVar = 'I am outside!';

function innerFunc() {

console.log(outerVar); // => logs "I am outside!"

}

innerFunc();

}

outerFunc();


Open the demo.

Inside the innerFunc() scope, the variable outerVar is accessed from the lexical scope. That's known already.

Note that innerFunc() invocation happens inside its lexical scope (the scope of outerFunc()).

Let's make a change: innerFunc() to be invoked outside of its lexical scope: in a function exec(). Would innerFunc() still be able to access outerVar?

Let's make the adjustments to the code snippet:


function outerFunc() {

let outerVar = 'I am outside!';

function innerFunc() {

console.log(outerVar); // => logs "I am outside!"

}

return innerFunc;

}

function exec() {

const myInnerFunc = outerFunc();

myInnerFunc();

}

exec();


Open the demo.

Now innerFunc() is executed outside of its lexical scope, but exactly in the scope of exec() function. And what's important:

innerFunc() still has access to outerVar from its lexical scope, even being executed outside of its lexical scope.

In other words, innerFunc() closes over (a.k.a. captures, remembers) the variable outerVar from its lexical scope.

In other words, innerFunc() is a closure because it closes over the variable outerVar from its lexical scope.

The JavaScript closure

You've made the final step to understanding what a closure is:

The closure is a function that accesses its lexical scope even executed outside of its lexical scope.

Simpler, the closure is a function that remembers the variables from the place where it is defined, regardless of where it is executed later.

A rule of thumb to identify a closure: if inside a function you see an alien variable (not defined inside that function), most likely that function is a closure because the alien variable is captured.

In the previous code snippet, outerVar is an alien variable inside the closure innerFunc() captured from outerFunc() scope.

Let's continue with examples that demonstrate why the closure is useful.

5. Closure examples

5.1 Event handler

Let's display how many times a button is clicked:


let countClicked = 0;

myButton.addEventListener('click', function handleClick() {

countClicked++;

myText.innerText = `You clicked ${countClicked} times`;

});


Open the demo and click the button. The text updates to show the number of clicks.

When the button is clicked, handleClick() is executed somewhere inside of the DOM code. The execution happens far from the place of the definition.

But being a closure, handleClick() captures countClicked from the lexical scope and updates it when a click happens. Even more, myText is captured too.

5.2 Callbacks

Capturing variables from the lexical scope is useful in callbacks.

A setTimeout() callback:


const message = 'Hello, World!';

setTimeout(function callback() {

console.log(message); // logs "Hello, World!"

}, 1000);


The callback() is a closure because it captures the variable message.

An iterator function for forEach():


let countEven = 0;

const items = [1, 5, 100, 10];

items.forEach(function iterator(number) {

if (number % 2 === 0) {

countEven++;

}

});

countEven; // => 2


Open the demo.

The iterator is a closure because it captures countEven variable.

5.3 Functional programming

Currying happens when a function returns another function until the arguments are fully supplied.

For example:


function multiply(a) {

return function executeMultiply(b) {

return a * b;

}

}

const double = multiply(2);

double(3); // => 6

double(5); // => 10

const triple = multiply(3);

triple(4); // => 12


Open the demo.

multiply is a curried function that returns another function.

Currying, an important concept of functional programming, is also possible thanks to closures.

executeMultiply(b) is a closure that captures a from its lexical scope. When the closure is invoked, the captured variable a and the parameter b are used to calculate a * b.

5.4 Encapsulation

Another good application that I enjoy is the ability to implement the encapsulation of a module.

Suppose you have a task to implement stack data structure: you can only push or pop items to the stack.

The regular JavaScript array provides both array.push() and array.pop() methods.

Here's a simple implementation of a stack:


function Stack() {

const items = []

return items;

}

const stack = Stack();

stack.push(3)

stack.push(2)

stack.push(1)

console.log(stack.pop()); // logs 1

stack.length = 0; // erases the stack

console.log(stack.pop()); // logs undefined (broken!)


Open the demo.

Yes, the push and pop operations are supported. But there's a problem: the entire array object is exported, and you can easily erase the stack using stack.length = 0, or do any other operations that are not permitted normally on a stack.

Let's make the Stack implementation encapsulated: allow only push or pop operations to be possible. That's exactly where the closure can help:


function Stack() {

const items = [];

return {

push(item) {

items.push(item);

},

pop() {

return items.pop();

}

}

}

const stack = Stack();

stack.push(3)

stack.push(2)

stack.push(1)

console.log(stack.pop()); // logs 1

stack.length = 0; // Does nothing!

console.log(stack.pop()); // logs 2 (works!)


Open the demo.

This time push() and pop() methods are closures that close over items array. What's interesting is that items variable is now private: it is accessible only inside Stack scope, but not outside.

Calling stack.length has no effect: items is not accessible outside Stack scope.

That was an example of another wonderful benefit of closures: you can use them to create true encapsulation with private variables.

6. Conclusion

The scope rules the accessibility of variables. There can be a function or a block scope.

The lexical scope allows a function scope to access statically the variables from the outer scopes.

Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.

Closures allow event handlers, callbacks to capture variables. They're used in functional programming. Moreover, you could be asked how closures work during a Frontend job interview.

What about a challenge? 7 Interview Questions on JavaScript Closures. Can You Answer Them?

Do you have any closure questions? Ask me in a comment below!