DEV Community

Cover image for What the Hell is Closure in JavaScript?

What the Hell is Closure in JavaScript?

Royal Jain on February 27, 2024

You might have heard the term "closure" tossed around in JavaScript conversations and tutorials, but what the hell is it really? What is...
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

.. a closure is a function that remembers the variables from the place where it was defined,

This isn't correct. A closure is not a function, and ALL functions form closures with their surrounding scope, there isn't a special type of function that does this.

Collapse
 
royaljain profile image
Royal Jain CodeParrot

The diagram in your article is very good. Function + surrounding state

A closure is a function that remembers the variables from the place where it was defined is a simpler way of saying that IMO which can be understood by everyone

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Not really...

If that definition were correct, there would be no point having separate words for closure and function, since every function has access to its surrounding scope in this way.

Thread Thread
 
royaljain profile image
Royal Jain CodeParrot

Remembers is the keyword here

Every function has access but not every function remembers

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

They do. All functions are the same in this respect.

From MDN:

In JavaScript, closures are created every time a function is created, at function creation time.

Every function has an associated closure, remembering the lexical environment in which it was created.

Thread Thread
 
royaljain profile image
Royal Jain CodeParrot

No, they don’t. They access the variables again which are in their lexical scope. In Closure, they store the variables and their values. Which is what your diagram signifies - function + state

To check this - just define a global variable console log in a function change the value and try again. New value will be printed meaning it doesn’t remember it accesses.