This post explains how the with statement works in JavaScript and why its use is discouraged.
with (object) statementintroduces the properties of object as local variables in statement. Example (the braces are optional for single statements, but it is recommended to add them):
> with({ first: "John" }) { console.log("Hello "+first); } Hello JohnIts intended use is to avoid redundancy when accessing an object several times.
foo.bar.baz.bla = 123; foo.bar.baz.yadda = "abc";with turns this into:
with(foo.bar.baz) { bla = 123; yadda = "abc"; }There is one similar case in JavaScript where the properties of an object are turned into variables and that is the global object window. All of its properties are global variables and vice versa. While new global variables are automatically added to window, the with statement works differently: variables that are declared inside it are not added to its argument, but to the surrounding function, where they still exist after leaving it.
> with({}) { var x = "abc"; } > x 'abc'
> function foo() { "use strict"; with({}); } SyntaxError: strict mode code may not contain 'with' statementsBest practice: Don’t use a with statement.
with(foo.bar.baz) { console.log("Hello "+first+" "+last); }Do use a temporary variable with a short name.
var b = foo.bar.baz; console.log("Hello "+b.first+" "+b.last);If you don’t want to expose the temporary variable b to the current scope, you can use an IIFE:
(function() { var b = foo.bar.baz; console.log("Hello "+b.first+" "+b.last); }());You also have the option of making the object that you want to access a parameter of the IIFE:
(function(b) { console.log("Hello "+b.first+" "+b.last); }(foo.bar.baz));
function foo(arg) { with(arg) { console.log("arg: "+arg) } }Interaction:
> foo("Hello"); arg: Hello // parameter arg > foo({}); arg: [object Object] // parameter arg > foo({ arg: "Hello" }); arg: Hello // property arg.argThere are thus two problems that the with statement causes:
with violates lexical scope, making program analysis (e.g. for security) hard to infeasible.