So, I’ve known for a long time that the
arguments object that is available in a function is
a bit “odd”, but until recently I didn’t realize how odd.
Soon, I was on the plane and with nothing really to do and my chromebook in my carry-on I decided to do some experimentations with some different vanilla-js syntaxes for doing the same thing. Nothing serious, just wanted to play around.
However, I quickly stumbled onto something that I kind of blew my mind.
Here is a extremely simplified version what I did:
expected is not a function then I wanted to wrap it into a function, and
returning the original value that was given in it’s place.
So, I tried passing it a function:
Cool, but then I tried it with something that wasn’t a function:
I expected the return of
fn() to be
1. However, much to my surprise, I got
a reference back to
fn itself… “Huh?” my former self though. I opened
up the developer console, and added a breakpoint inside
clean. Shockingly – at least to
me at the time – was that
capturedArugments did not point at the value
I originally had passed in… Instead, it pointed at the function that I had
I had a feeling that I had stumbled onto something that I should have been aware of a long time ago. I wrote another function, something even simplier, in an attempt to understand what was going on.
And no matter what numbers that I fed into the function, the result would always come back
15. In fact, no
matter what data-type or object I fed in, I would always get
15. Even more specifically, the only way
that I would not get back
15, was when I invoked the function with less than two arguments, eg.
Then I tried something else.
And lo-and-behold, the same result. It appeared like the
and the variables of the function are linked. Change one and it effects the other.
By this time, I was off the plane and was able to reconnect the internets – my
source of information, and was able to find that this is a fairly well documented
“feature” of the
arguments object. I just had never heard of it.
Note that this behavior is no longer supported when in strict mode:
I’m really not sure when one would ever want to do this, but I’m sure some where in some code base this trick is used. But I’m more surprised that I just had never heard of it until now!