TIL mysterious with keyword in Javascript
POSTED ON:
TAGS: javascript obsolete
There's a lot of ancient Javascript code that you really shouldn't use.
This is one of them. MDN - with Statement
Example from the MDN:
The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.
let a, x, y;
const r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
Example from the blog postJavaScript's Forgotten Keyword (with):
with (console) {
log('I dont need the "console." part anymore!');
}
To reword that hopefully a little more simply: when you write an identifier in your code (like log or join in the above code snippet) there is a chain of objects that JavaScript looks at, and if one of those objects has a property with the same name as the identifier you wrote in your code, JavaScript uses the value of that property.
There's a lot of cons with the with
statement.
Via the MDN - with Statement:
-
Pro: The with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty.
-
Contra: The with statement forces the specified object to be searched first for all name lookups.
-
Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object.
-
Contra: Code using with may not be forward compatible, especially when used with something other than a plain object.
It's so destructive, you can't even use it in Strict Mode
.
Related TILs
Tagged: javascript