Course contentsShow
← JavaScript
Lesson 1463 of 2,72332. JavaScript in the BrowserFree lesson

Let, Const, and the Global Scope

Why let and const in global scope don't create window properties and what that means for your code.

Let, Const, and the Global Scope

You'll learn why modern variable declarations behave differently than you might expect in the global scope.

The Surprising Behavior

When you declare a variable with var in the global scope (outside any function or block), it automatically becomes a property of the window object in browsers. However, variables declared with let or const in the global scope do NOT become window properties.

How It Works

// Global scope
var oldSchool = 'I am a window property';
let modern = 'I am not a window property';
const alsoModern = 'Neither am I';

console.log(window.oldSchool);  // 'I am a window property'
console.log(window.modern);     // undefined
console.log(window.alsoModern); // undefined

// But they're still accessible globally
console.log(modern);      // 'I am not a window property'
console.log(alsoModern);  // 'Neither am I'

Why This Matters

This difference exists for encapsulation and safety. By not polluting the window object, let and const reduce the risk of accidentally overwriting built-in browser APIs or conflicting with other scripts.

Think of it like living in an apartment: var leaves your belongings in the shared hallway where anyone can trip over them, while let and const keep them safely inside your unit—still yours to use, but not cluttering common spaces.

Your global let and const variables live in what's called the "global lexical environment," a separate space from window properties, even though they're still globally accessible.

Practical Impact

This means you can safely use let and const at the top level of your scripts without worrying about namespace collisions with the browser's built-in properties.

Key Takeaway: Global let and const create truly scoped variables that don't become window properties, making your code safer and more predictable than using var.