Facebook Pixel
let, const, and the Global Object in JavaScript

Why does var become a property of window but let does not?

The answer

It is a legacy behavior. var was designed before ES6 to attach to the global object. let and const were designed to be cleaner: they live in a separate global lexical environment and do not pollute window.

More FAQs in let, const, and the Global Object in JavaScript

No. let and const at the top level live in a global lexical environment that is separate from the window object. They are still global (accessible everywhere in the script), but they are not properties of window. var does become a property of window.

No. In ES modules, top-level let, const, and var are module-scoped, not global. They are only accessible outside the module if explicitly exported. This is the cleanest behavior and prevents global pollution.

Use typeof. typeof b !== 'undefined' checks if b exists without throwing, even though b is not a property of window. Do not use 'b' in window, because let globals do not attach to window.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

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.
Please Login.
Please Login.
Please Login.