Skip to Main Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced content levelIntermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

with

In Chapter 4, we discussed variable scope and the scope chain -- a list of objects that are searched in order, to perform variable name resolution. The with statement is used to temporarily modify the scope chain. It has the following syntax:

with (object)
    statement

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

In practice, you can use the with statement to save yourself a lot of typing. In client-side JavaScript, for example, it is common to work with deeply nested object hierarchies. For instance, you may have to type expressions like this one to access elements of an HTML form:

frames[1].document.forms[0].address.value

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

with(frames[1].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 frames[1].document.forms[0]. That object is temporarily part of the scope chain and is automatically searched when JavaScript needs to resolve an identifier like address.

Despite its occasional convenience, the use of the with statement is frowned upon. JavaScript code that uses with is difficult to optimize and may therefore run more slowly than the equivalent code written without the with ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
Coding with JavaScript For Dummies

Coding with JavaScript For Dummies

Chris Minnick, Eva Holland

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata