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.