Yusuf Yalim Yusuf Yalim - 2 months ago 10
Javascript Question

Why anonymous functions on javascript have name?

I am reading a great book named "Secrets of the JavaScript Ninja" written by John Resig & Bear Bibeaoult. In chapter 3.2, It gives an example;

var canFly = function(){ return true; };

Then it says;

An anonymous function is created and assigned to a global variable named canFly. Because of JavaScript's functional nature, the function can be invoked through this reference as canFly(). In this respect, it's almost functionally equivalent to declaring a named function named "canFly", but not quite. One major difference is that the function's name property is "", not "canFly".

But when I am trying to execute the example on Chrome's Developer Tools and inspect the name property of canFly function, it returns value of "canFly" instead of an empty string.

// > "canFly"

Did anonymous functions that assigned to a variable have no name in earlier days? If so, what is changed? Or did authors make a mistake?

Answer Source

In theory anonymous functions are anomymous, meaning nameless. This was how it was originally implemented and for more than ten years everybody was fine with this.

Then two things happened: the whole Web2.0/ajax movement where people started implementing UI features commonly found on desktop apps in web pages and node.js. These two in combination forced more and more developers to treat javascript as a serious language and once people got comfortable with javascript they started writing really large codebases.

This led to complaints about the debuggability of javascript. There were numerous from not having any useful debugger (which led us to really good debuggers in browsers that is in my opinion second best only to MS Visual Studio) to not knowing what function a console.log comes from (because they're anonymous).

This led to browser and js engine developers to implement code that tries to guess the "name" of nameless functions.

In theory this feature is wrong because you can't always guarantee that the name you're guessing is how the function is called (for example if the function is assigned to several different variables). In practice something that works 90% of the time is better than nothing at all.