-1

What does the Javascript 'with' keyword do? I tried searching online but no luck. Thanks.

ranja
  • 1

5 Answers5

8

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.

Community
  • 1
  • 1
Zed
  • 57,028
  • 9
  • 76
  • 100
1

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());
Joseph
  • 25,330
  • 8
  • 76
  • 125
0

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

James
  • 69
  • 2
0

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

Gordon Gustafson
  • 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
0

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.

Community
  • 1
  • 1
Maiku Mori
  • 7,419
  • 2
  • 40
  • 52