Execute Program

Modern JavaScript: Function Name Property

Welcome to the Function Name Property lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Normally, defining a function automatically assigns it to a variable. If we declare a function five(), we can use the variable five to refer to our function.

  • >
    function five() { return 5; }
    five();
    Result:
  • Functions declared like this have a name property. As you might expect, the name of a function five() is the string 'five'.

  • >
    function five() { return 5; }
    five.name;
    Result:
    'five'Pass Icon
  • Functions don't have to have names, though. If a function is created without a name, its name will be the empty string, ''. These are called "anonymous" functions.

  • >
    (
    function() { return 5; }
    ).name;
    Result:
    ''Pass Icon
  • If we immediately assign an anonymous function to a variable, that variable's name will become the function's name. (Functions created like this are still called "anonymous" because there's no name specified in the function() { ... } definition.)

  • >
    const five = function() { return 5; };
    five.name;
    Result:
    'five'Pass Icon
  • The function remembers its original name, even if it's assigned to a different variable.

  • >
    const five = function() { return 5; };
    const alsoFive = five;
    alsoFive.name;
    Result:
    'five'Pass Icon
  • >
    const five = function() { return 5; };
    const functions = [five];
    functions[0].name;
    Result:
    'five'Pass Icon
  • Anonymous functions only get a name if they're assigned directly to a variable. If we put the function in an array, for example, it won't get the array's name; instead, it will have no name.

  • >
    const functions = [function() { return 5; }];
    functions[0].name;
    Result:
    ''Pass Icon
  • Arrow function syntax doesn't give us any place to specify the function's name. As a result, arrow functions are always anonymous. However, like normal functions, they do get a name if they're assigned directly to a variable.

  • >
    (
    () => 1
    ).name;
    Result:
    ''Pass Icon
  • >
    const one = () => 1;
    one.name;
    Result:
    'one'Pass Icon