Chapter 10. With statements

 

This chapter covers

  • Why the with statement is controversial
  • How with statements work
  • Code simplification with with
  • Tricky with gotchas
  • Templating with with

The with statement is a powerful, frequently misunderstood, and controversial feature of JavaScript. A with statement allows us to put all the properties of an object within the current scope, allowing us to reference and assign to them without having to prefix them with a reference to their owning object.

It’s important to know that this statement’s continued existence within JavaScript is fleeting. The ECMAScript 5 specification prohibits its use in strict mode, to the extent of considering it a syntax error.

Moreover, the with statement, even prior to ECMAScript 5, was not without its detractors. One of these high-profile skeptics is none less than Douglas Crockford (JavaScript Ninja Extraordinaire, inventor of JSON, and author of JavaScript: The Good Parts), who, in 2006, published a famous blog post titled “with Statement Considered Harmful,” in which he states:

If you can’t read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.

10.1. What’s with “with”?

10.2. Real-world examples

10.3. Importing namespaced code

10.4. Testing

10.5. Templating with “with”

10.6. Summary

sitemap