I'm thinking that stuff like with(Math){document.body.innerHTML= PI}
wouldn't exactly be good practise.

- 14,980
- 18
- 49
- 57
-
see also [Are there legitimate uses for JavaScript's “with” statement?](http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement) – ephemient Dec 28 '10 at 19:40
-
why not `document.body.innerHTML= Math.PI` – Mark Baijens Dec 28 '10 at 19:45
3 Answers
I would call it bad practice, considering how it affects the scope chain.
Take a look at this article from Douglas Crockford: "with Statement Considered Harmful"

- 43,482
- 6
- 101
- 102
-
So you should use this instead? `var here = Math; document.body.innerHTML = here.PI`? (I know you wouldn't do that, it's just an example. – DarkLightA Dec 28 '10 at 19:40
-
@DarkLightA - Generally I just type out the full reference name. There are few cases where I will alias longer objects, but for the most part I stick with the full name, if only to make it easier to read later. – Matt Dec 28 '10 at 19:41
-
-
@DarkLight: That's a different Matt. He only has 5.5K reputation. Mouseover the name in the comment or look at the userid in the URL. – SLaks Dec 28 '10 at 23:54
The short summary of the link in Matt's answer is that the problem with using the "with" statement is that the variables within the "with"'s block are ambiguous. Using the following example:
with(foo.doo.diddly.doo){
bar = 1;
baz = 1;
}
If you're not absolutely certain that foo.doo.diddly.doo has the bar or baz properties, you don't know if the bar and baz within the with statement are getting executed, or some global bar and baz. It's better to use variables:
var obj = foo.doo.diddly.doo;
obj.bar = 1;
obj.baz = 1;
In your example, though, Math is hardly a long enough term to justify even using a variable, but I'm guessing you have a more verbose application in mind than you've used for the question.

- 8,534
- 1
- 26
- 39
If you access (nested) object properties once, then there is no need "cache" them.
But if you access them more then once, then you should store a reference in a local variable. This has two advantages:
- (nested) properties don't need to be lookup up more then once (potentially in the inheritance chain which is slow!).
- Especially global objects (but any object that is not in the current scope) only needs to be looked up once in the scope chain. Subsequent access will be faster.
And now the connection to with
:
It generates a new scope at beginning of the current scope chain. That means that any access to other variables/objects will cost at least one scope lookup more, even to variables that are local to the function.

- 795,719
- 175
- 1,089
- 1,143