Calling toString on a javascript function returns source code

Sergi Papaseit picture Sergi Papaseit · Mar 16, 2011 · Viewed 39.6k times · Source

I just found out that when you call toString() on a javascript function, as in myFunction.toString(), the source code of that function is returned.

If you try it in the Firebug or Chrome console it will even go as far as formatting it nicely for you, even for minimized javascript files.
I don't know what is does for obfuscated files.

What's the use of such a toString implementation?

Answer

HoLyVieR picture HoLyVieR · Mar 16, 2011

It has some use for debugging, since it lets you see the code of the function. You can check if a function has been overwritten, and if a variable points to the right function.

It has some uses for obfuscated javascript code. If you want to do hardcore obfuscation in javascript, you can transform your whole code into a bunch of special characters, and leave no numbers or letters. This technique relies heavily on being able to access most letters of the alphabet by forcing the toString call on everything with +"" (example : (![]+"")[+[]] is f ). Some letters like v can only be accessed by calling toString on a native function like [].sort. The letter v is important for obfuscated code, since it lets you call eval, which lets you execute anything, even loops, without using any letters. Here is an example of this.