Facebook Pixel

Is a closure the function or the function plus the environment in JavaScript?

The function plus the environment. A closure is the combination of a function and its lexical environment (the variables it closes over). The function object holds a hidden reference to that environment.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How Closures Work With Lexical Scope

Closures are a consequence of lexical scope. Functions store a reference to their lexical environment at creation time. When called later, the outer reference is the stored one, so the function can access outer variables even after the outer function has returned.

Because the inner function holds a reference to the outer lexical environment. As long as the inner function exists, the garbage collector cannot free the environment. The scope chain persists.

No. Each call creates a separate lexical environment. So makeAdder(5) and makeAdder(10) each have their own x. The closures are independent and do not share state.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.