JavaScript Scoping, Closures, and Polyfills
Problem
Explain the difference between var and let, what a closure is, and what a polyfill does.
Be ready to discuss
var: function-scoped, hoisted and initialised toundefined, redeclarable in the same scope, and attached to the global object at top level.let/const: block-scoped, hoisted into the temporal dead zone so access before declaration throws a ReferenceError, and not redeclarable in the same scope.- The classic loop bug:
var iin aforloop shares one binding across all iterations, whilelet icreates a fresh binding per iteration - and how the pre-ES6 fix was an IIFE. - Closures: a function keeps a reference to its enclosing lexical environment even after the outer function returns, because the scope chain lives on as long as the inner function does.
- What closures are used for: data privacy and encapsulation, factory functions, module pattern, memoization, and partial application/currying.
- Closure pitfalls: unintended memory retention when a long-lived closure captures a large object.
- Polyfills: runtime code that implements a standard API missing from an older environment (e.g.
Array.prototype.includes,Promise,Object.assign). - Polyfill vs transpilation: Babel rewrites syntax, polyfills supply missing built-ins - and why feature detection should gate a polyfill rather than UA sniffing.
asked …