What does the Javascript 'with' keyword do? I tried searching online but no luck. Thanks.
-
9Funny, I searched for "javascript with keyword" on google and got a great explanation from the very first result – Eric Petroelje Oct 09 '09 at 19:37
-
Part 2: in what version of javascript does it first appear? – Joel Coehoorn Oct 09 '09 at 19:39
-
Yep. with-keyword, or with-statement and you're on track. – Zed Oct 09 '09 at 19:39
-
1Please don't use `with`. – kangax Oct 09 '09 at 19:40
-
@Eric: Funny, I tried that and it's a page talking about the `this` keyword, no mention of `with`. But the sentiment is valid. – Joel Coehoorn Oct 09 '09 at 19:40
-
I am with kangax Do NOT use "with" please. – Mark Schultheiss Oct 09 '09 at 20:02
-
@Joe: I think @Eric searched with quotes. – Roatin Marth Oct 09 '09 at 20:13
5 Answers
You can save some typing with it:
with(Math) {
var x= cos(PI);
var y= sin(PI);
}
Here's an SO question on its legitimacy.
It's similar to VB's With statement, where it creates a block and allows you to use whatever you put in the with statement inside the block.
Here's a reference.
And an example:
function generateNumber()
{
with(Math)
{
var x, y ,z
x= cos(3 * PI) + sin (LN10)
y= tan(14 * E)
z=(pow(x,2) + pow(y,2)) * random()* 100;
}
return z;
}
document.write(generateNumber());

- 25,330
- 8
- 76
- 125
It creates a block of code that allows you to use whatever's inside the with statement inside that block.
Examples here: http://www.devx.com/tips/Tip/5700

- 69
- 2
It allows you to perform operations in the context of a certain object, but it has some downsides. It can sometimes make your references ambiguous. It usually isn't a problem, but if you just type a few extra characters you can be 100% sure that you're the browser's doing what you think its doing. :D

- 40,133
- 25
- 115
- 157
-
"In the context of a certain object" sounds ambiguous. Context, for example, is often understood as `this` value of a function. Another interpretation is execution context of a function. `with`, of course, does not affect either — it merely injects an object in question in front of current scope chain. – kangax Oct 11 '09 at 07:06
There are some neat tricks you can do with it, but other then that using with is discouraged.
See this SO answer for more info. Make sure you read Shog9's answer.

- 1
- 1

- 7,419
- 2
- 40
- 52