Deprecating features in JavaScript is rare. Only one feature in the language’s history has been officially deprecated: ‘with’ statements.
The ‘with’ statement was introduced early in JavaScript’s history. Its purpose was to simplify working with objects by providing a shortcut to access object properties.
The ‘with’ statement allows you to access the properties of the car object directly, without needing to type car.make, car.model, and car.year.
Why Was with Deprecated?
The main issue was ambiguity. Because the with statement modifies the scope, it became difficult for both developers and JavaScript engines to know which variables or properties were being referred to.
What will this code print?
Will it print ‘Toyota’ from the car object, or ‘Honda’ from the showMake function’s scope? The ambiguity here is the problem. It could easily lead to bugs that are hard to track down.
The answer: ‘Toyota’
The with statement extends the scope chain, so when with (car) is used, it effectively puts the properties of the car object into the scope.
In the showMake function, when console.log(make) is called inside the with (car) block, JavaScript first looks for make within the car object. Since car has a make property with the value ‘Toyota’, it finds this first and prints ‘Toyota’.
If the car object did not have a make property, JavaScript would then look for make in the surrounding scope, where it would find the ‘Honda’ value. But in this case, because car has a make property, ‘Toyota’ is printed.
Where We Stand Today (2024)
The with statement is still part of JavaScript today, but it’s considered bad practice. It can cause confusing and unpredictable behavior.
This happens because it changes the scope chain, making it hard to tell which variables are being used. This ambiguity can lead to bugs that are tough to find.
For these reasons, it’s best to avoid using with in your code.
How to Avoid Using with
Instead of using with, you should reference object properties directly. If you’re trying to shorten the syntax, consider using destructuring:
This code achieves a similar effect to the ‘with’ statement but without the pitfalls. Destructuring is clear, unambiguous, and widely supported in JavaScript.
The ‘with’ statement is often cited as the only feature ever deprecated in JavaScript, but that’s not entirely true.
While it’s one of the most prominent and well-known deprecated features, it’s not alone. Other features, such as arguments.callee in strict mode and certain uses of eval(), have also faced deprecation or strong discouragement.