O'Reilly logo

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Miscellaneous Statements

This section describes the remaining three JavaScript statements—with, debugger, and use strict.

with

In The Scope Chain, we discussed the scope chain—a list of objects that are searched, in order, to perform variable name resolution. The with statement is used to temporarily extend the scope chain. It has the following syntax:

with (object)
    statement

This statement adds object to the front of the scope chain, executes statement, and then restores the scope chain to its original state.

The with statement is forbidden in strict mode (see “use strict”) and should be considered deprecated in non-strict mode: avoid using it whenever possible. JavaScript code that uses with is difficult to optimize and is likely to run more slowly than the equivalent code written without the with statement.

The common use of the with statement is to make it easier to work with deeply nested object hierarchies. In client-side JavaScript, for example, you may have to type expressions like this one to access elements of an HTML form:

document.forms[0].address.value

If you need to write expressions like this a number of times, you can use the with statement to add the form object to the scope chain:

with(document.forms[0]) {
    // Access form elements directly here. For example:
    name.value = "";
    address.value = "";
    email.value = "";
}

This reduces the amount of typing you have to do: you no longer need to prefix each form property name with document.forms[0]. That object is temporarily part ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required