with Keyword

Examples

Using with

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

let a, x, y;
const r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}


Avoiding with by destructuring properties into the current scope

You can usually avoid using with through property destructuring. Here we create an extra block to mimic the behavior of with creating an extra scope - but in actual usage, this block can usually be omitted.

let a, x, y;
const r = 10;

{
  const { PI, cos, sin } = Math;
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}


Using with with a proxy to create a dynamic namespace

with will transform every variable lookup to a property lookup, while Proxies allow trapping every property lookup call. You can create a dynamic namespace by combining them.

const namespace = new Proxy({}, {
  has(target, key) {
    // Avoid trapping global properties like `console`
    if (key in globalThis) return false;
    // Trap all property lookups
    return true;
  },
  get(target, key) {
    return key;
  },
});

with (namespace) {
  console.log(a, b, c); // logs "a b c"
}