Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

JavaScript with() statement

The JavaScript language's "with" statement was intended to provide a shorthand for writing recurring access to objects. So instead of writing

foo.bar.baz = "hello"
foo.bar.zip = "world"

You can write,

with ( foo.bar ) {  baz = "hello"; zip = "world" }

which looks a lot nicer. What happens internally is, the JavaScript engine adds the object to the scope chain used when evaluating the statements within the block. There is a temporary augmentation of the execution context to the scope chain. As for the beginners, you need to understand that "with" is generically considered a harm in the JavaScript world, an explanation of which is as follows. Kindly continue reading. And as for the experts, you are welcome to analyse the context.

First, let us understand the advantage of using the "with" statement. It reduces the need to repeat a lengthy object reference without performance penalty - as the scope chain change, induced by this statement, is NOT computationally expensive.

Now, let us inquire about the hows and whys of accusing this statement harmful. Consider an unscoped / unqualified variable used in the body matches a property in the scope chain. The JavaScript interpreter finds out the value of that variable by waking up the scope chain available to the execution context. The with() statement takes the given object and pushes it to the current scope for the duration of that with() block. Once the block has finished executing, the given object is popped off and the scope chain returns to its previous state.

In simpler terms, the with() statement appends an extra set of variables to the beginning of the scope chain. And by virtue of this extra item, the JavaScript engine has to loop through the with() variables, the local ones, and then the global ones - simply to access a variable. So all identifiers that aren't members of the specified object will be found more slowly inside a with() block. Also with() ambiguously makes it hard for a programmer to decide whether an unqualified name will be found along the scope chain, and if so, in which object.

The statement essentially gives the local variables all the performance drawbacks of the global ones, and in turn derails JavaScript optimization.