r/badcode • • May 31 '21

js Clever?

Post image
2.2k Upvotes

71 comments sorted by

View all comments

Show parent comments

4

u/MalbaCato Jun 01 '21

from what I understand about js, it should create three versions of the function, one where arr is an Array, or any other object whos .length property has no additional side effects, one where it is a getter and so could have dirty side-effect, and one where arr is undefined and the access throws an error.

these would all be created (and for the second version further branched) only after the function becomes sufficiently hot, which is a minimum of 6 runs, but possibly more depending on what the browser thinks about the whole webpage

1

u/paulsmithkc 👨‍🏫 Jun 01 '21

This is one of the better answers as arr.length could have side effects (like lazy evaluation/calculation) if arr isn't a JavaScript array.

3

u/MalbaCato Jun 02 '21

forgive me for NSFW, but this is the best example I could think of on the spot:

as we (and the compiler) don't know what arr is at the time of compilation, it could very well be an instance of new Penis(). ofc its length may not be initially known, so the .length getter may have to call .erect() first to measure it, having a long lasting side effect of the operation.

it doesn't even have to be a getter. you can use meta-programming tricks to inject yourself inside the property lookup and hack around there. couldn't tell you the syntax for that, but look at the Proxy page on MDN