with makes it harder to evolve JavaScript

[2013-06-19] dev, javascript, jslang
(Ad, please don’t block)
JavaScript’s with statement has been deprecated for a while [1]: it slows down your code and is forbidden in strict mode. Additionally, it makes it harder to evolve the language, because code that uses it is more brittle.

To see why, let’s look at the following function:

    function foo(someArray) {
        var values = ...;  // (1)
        with (someArray) {
            ...
            values.someMethod(...);  // (2)
            ...
        }
    }
    var myData = ...;
    foo(myData);  // (3)
You can prevent the function call in line (3) from working, even if you don’t have access to the array myData.

How? By adding a property to Array.prototype. For example:

    Array.prototype.values = function () {
        ...
    };
Now the code in line (2) calls someArray.values.someMethod() instead of values.someMethod(). The reason for that is that, inside the with statement, values now refers to someArray.values and not the local variable from line (1), any more.

This is not just a thought experiment, an array method values was recently added to Firefox and broke the TYPO3 content management system. Brandon Benvie (comment 13) figured out what went wrong.

Reference:

  1. JavaScript’s with statement and why it’s deprecated