Search code examples
javascriptgoogle-chromeanonymous-functionfunction-expression

Anonymous function expression in Google Chrome


I am using Google Chrome version 52 64-bit. I found out that if I use anonymous function expression ex.

//  Anonymous function expression 
var expressionFunc = function(){
    return true;
};

The variable expressionFunc will hold the assigned anonymous function, But it is also adding a name property expressionFunc to this function. So if I do expressionFunc.name in the console, It will give me expressionFunc.

From what I know this anonymous function expression should stay anonymous, And the function referenced by the variable should not contain the variable name in the name property of the function.

Why is chrome assigning name property to an anonymous function?


Solution

  • This page:

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name

    Says this

    Browsers that implement ES6 functions can infer the name of an anonymous function from its syntactic position. For example:

    var f = function() {};
    console.log(f.name); // "f"
    

    There's no particular explanation on that page.

    This page

    http://www.2ality.com/2015/09/function-names-es6.html

    Says this

    With regard to names, arrow functions are like anonymous function expressions:

         const func = () => {};
         console.log(func.name); // func
    

    From now on, whenever you see an anonymous function expression, you can assume that an arrow function works the same way.

    The answer at https://stackoverflow.com/a/37488652/1048572 (referenced by @bergi) is pretty comprehensive, and points to the source in the specification.