The name of a function

Problem : getting the name of a function for debugging purposes. The only thing available to do this is the function object.

f.name

Very convenient and implemented in most browsers, the name property provides the name. The only problem of this method is that it is not standard. It is not a part of ECMAScript 3 or 5.

Extracting from f.toString()

ECMAScript 3/5 Function.prototype.toString():

An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent.

The grammar rule for FunctionDeclaration is :
function Identifier ( FormalParameterListopt ) { FunctionBody }

Pretty cool and standard. The following code returns the function name in any ECMAScript compliant environment :

function extractFunctionName(f){
    var s = Function.prototype.toString.call(f); // f.toString may be overridden 
        
    var leftParenthesisIndex = s.indexOf('(');
    var afterFunctionIndex = s.indexOf("function") + "function".length;
     
    return afterFunctionIndex < leftParenthesisIndex ?
              s.substring(afterFunctionIndex, leftParenthesisIndex).trim():
              "";
}

Bonus : the anonymous function

When asking to Firebug the following :

console.log( extractFunctionName( function(){} ) );

The answer is “(an empty string)”. Hmm… Remember the Identifier earlier ?
The definition of Identifier is IdentifierName but not reserved word. IdentifierName is either IdentifierStart or
IdentifierName IdentifierPart. In any case, an IdentifierName begins with an IdentifierStart which is :

IdentifierStart ::
UnicodeLetter
$
_
\ UnicodeEscapeSequence

To conclude, an Identifier cannot be empty.

I call this a standard bug! Luckily, the TC-39 committee is fully aware of it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s