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:
- The
with
statement can make code more ambiguous and harder to read. When reading the code, it becomes unclear where variables or
properties are coming from, as they can be from the object in the with
statement or any of its parent scopes.
- The
with
statement negatively impacts performance. JavaScript engines have a harder time optimizing code with with
because it adds uncertainty to variable lookups, which can result in slower execution.
- Using
with
can lead to bugs that are difficult to identify and troubleshoot. If a variable is not found in the object within the
with
statement or its parent scopes, JavaScript will create a new global variable instead, potentially leading to unexpected behavior.
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