Mastering the with() Statement in JavaScript
Introduction
The with statement in JavaScript extends the scope chain for a statement block. It allows you to access properties of a specified object directly, without repeatedly referencing the object. ⚠️ However, it is considered **bad practice** and is deprecated in strict mode due to readability and performance issues.
📌 What is with?
with lets you treat an object's properties as if they were variables within a block, removing the need to prefix them with the object name.
- ✔️ Shortens code by removing repetitive object references
- ⚠️ Not allowed in strict mode
- 🚫 Avoid in production — can cause ambiguity
💡 Syntax
Basic Syntax
with (object) {
// statements
}🧵 Example: Using with for Shorter Access
Accessing object properties without repetition
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
with (car) {
console.log(brand);
console.log(model);
console.log(year);
}
// Output:
// Toyota
// Corolla
// 2020⚠️ Why with is Discouraged
Note
Using with can lead to confusion when variables inside the block could be properties of the object or variables in the outer scope. This ambiguity makes code harder to debug and less predictable.
🚫 Example of Ambiguity
Ambiguous variable resolution
const obj = { a: 1 };
let a = 99;
with (obj) {
console.log(a); // Is this obj.a or variable a? -> 1
}🔍 Allowed in Non-Strict Mode Only
Strict mode restriction
"use strict";
const person = { name: "Alice" };
with (person) { // ❌ SyntaxError in strict mode
console.log(name);
}📊 Quick Reference Table
| Feature | Supported? |
|---|---|
| Works in non-strict mode | ✅ |
| Works in strict mode | ❌ |
| Recommended for production | ❌ |
>>"Just because you can shorten code doesn’t mean you should — clarity beats cleverness."
🔥 Summary
The with statement was designed for convenience but is now discouraged due to performance costs and ambiguous behavior. Modern JavaScript best practices recommend using **destructuring** or direct property access instead.