Course contentsShow
← JavaScript
Lesson 1021 of 2,72323. SymbolsFree lesson

Symbol.unscopables for With Statement Behavior

Control property visibility in deprecated with statements using Symbol.unscopables.

Symbol.unscopables for With Statement Behavior

What you'll learn: How Symbol.unscopables controls which properties are excluded from deprecated with statement scopes.

What Is Symbol.unscopables?

Symbol.unscopables is a well-known symbol that lets you specify which properties of an object should not be accessible as variables inside a with statement. Think of it as a "do not enter" list for certain properties when code uses the old with syntax.

The with statement (now deprecated and forbidden in strict mode) temporarily adds an object's properties to the scope chain. But sometimes you want specific properties to remain "out of reach" to avoid naming conflicts or unexpected behavior.

How It Works

An object's Symbol.unscopables property should be an object where keys are property names and values are booleans. If a property is set to true, it becomes "unscopable" — meaning it won't be found by the with statement.

const myObj = {
  included: 'I am accessible',
  excluded: 'I am hidden',
  [Symbol.unscopables]: {
    excluded: true
  }
};

with (myObj) {
  console.log(included);  // "I am accessible"
  console.log(excluded);  // ReferenceError: excluded is not defined
}

Real-World Usage

You'll rarely use this yourself, but built-in objects like Array.prototype use it. For example, newer array methods like values() are marked unscopable to prevent breaking old code that used with statements before those methods existed.

console.log(Array.prototype[Symbol.unscopables]);
// { values: true, keys: true, entries: true, ... }

Key Takeaway: Symbol.unscopables prevents specific object properties from being accessible inside with statements, primarily used by built-in objects to maintain backward compatibility with legacy code.