JavaScript's Forgotten Keyword: with
The article explains the obscure JavaScript 'with' keyword, demonstrating its syntax and behavior, detailing how it manipulates the scope chain, and outlining the numerous drawbacks—including strict‑mode prohibition, variable shadowing, security risks, performance penalties, and poor maintainability—that make its use inadvisable.
JavaScript development can be exciting, and occasionally you encounter obscure features like the rarely used with keyword.
Usage
You can use the with keyword to print a message to the console:
with
(
console
) {
log(
'I dont need the "console." part anymore!'
);
}with can also be used to merge an array into a string:
with
(
console
) {
with
([
'a'
,
'b'
,
'c'
]) {
log(join(
''
));
// outputs 'abc'
}
}What with does
According to MDN, when JavaScript looks for an identifier without an explicit namespace, it walks the scope chain; the with statement adds a given object to the top of that chain, so any identifier that matches a property of that object resolves to the property’s value, otherwise a ReferenceError is thrown.
In short, if an identifier such as log or join appears inside a with block, JavaScript first checks the object placed on the scope chain for a matching property and uses that value.
Example:
with
({
myProperty
:
'Hello world!'
}) {
console
.log(myProperty);
// prints "Hello world!"
}Why you should avoid with
It is forbidden in strict mode, and modern JavaScript modules and classes enable strict mode automatically, effectively removing the keyword from contemporary code.
Variable shadowing: identifiers inside a with block can be unintentionally overridden, leading to bugs such as returning NaN when Math.min or Math.max are shadowed.
Security risks: injecting untrusted objects (e.g., from a parsed JSON payload) into a with statement can allow attackers to overwrite identifiers and alter program behavior.
Performance: adding objects to the scope chain forces the engine to search more objects when resolving identifiers, slowing execution.
Social stigma: developers who use with are often ridiculed and may find their code harder to maintain.
Conclusion
The with keyword adds some quirky capabilities to JavaScript, but its disadvantages outweigh any benefits, and it is generally not recommended for use.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.