Today I Learned - Rocky Kev

TIL mysterious with keyword in Javascript

POSTED ON:

TAGS:

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:

It's so destructive, you can't even use it in Strict Mode.


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.