Why is this an issue?

The with statement introduces a new scope, where properties of an object can be accessed directly without having to specify the object’s name explicitly. However, using it is generally considered a bad practice and is strongly discouraged.

While it might seem convenient at first, it can lead to several issues:

As a result of these issues, ECMAScript 5 (ES5) strict mode explicitly forbids the use of the with statement. Strict mode was introduced to enhance code safety and maintainability, and it helps to catch potential issues and discourage the use of problematic language features.

let x = 'a';

let foo = {
  y: 1
};

with (foo) { // Noncompliant
  y = 4;     // Updates 'foo.y'
  x = 3;     // Does not add a 'foo.x' property; updates the variable 'x' in the outer scope instead
}

console.log(foo.x + " " + x); // Prints: undefined 3

Instead of using with, it’s best to write more explicit code, accessing object properties directly without relying on the with construct.

let x = 'a';

let foo = {
  y: 1
};

foo.y = 4;
foo.x = 3;

console.log(foo.x + " " + x); // Prints: 3 a

Resources

Documentation