Facebook Pixel

Do closures capture objects by reference or by value in JavaScript?

By reference to the variable. If you mutate the object's properties, the closure sees the changes. If you reassign the variable to a new object, the closure sees the new object (because it references the variable, not the original object).

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Closures Capture the Variable, Not the Value in JavaScript

The variable. A closure holds a reference to the variable, not a snapshot of its value. If the variable changes before the callback runs, the closure sees the updated value. This is why var in a loop logs the final value.

Because they all close over the same variable i. Closures capture the variable, not the value. When the callbacks run, i is the final value, so all callbacks log it.

Use let (creates a fresh binding per iteration), or an IIFE that passes the current value as a parameter (pass-by-value for primitives), or pass the value as an extra argument to setTimeout.

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.