javascriptfunction-expressionjavascript-function-declaration

Why Named Function Expression itself cannot assign Name to another Value?


var functionVariable = function functionExpressionName() {
    functionExpressionName = 1;
    console.log(functionExpressionName) // function
};

functionVariable();

If You run this example you can see we can not reassign to functionExpressionName anything. But this is also interesting we can reddeclare functionExpressionName and after this we can assign anything to functionExpressionName

var functionVariable = function functionExpressionName() {
    function functionExpressionName() {

    }

    functionExpressionName = 1;
    console.log(functionExpressionName); // 1
};

functionVariable();

Solution

  • If you enable strict mode, the error becomes a bit clearer:

    'use strict';
    var functionVariable = function functionExpressionName() {
        functionExpressionName = 1;
        console.log(functionExpressionName) // function
    };
    
    functionVariable();

    Uncaught TypeError: Assignment to constant variable

    The function name is un-reassignable inside the function, but you can create a new variable with the same name inside the function body. One way of looking at it is that the function name is declared with const just outside the function body:

    var functionVariable = (() => {
      const functionExpressionName = function () {
        functionExpressionName = 1; // Clearly wrong - functionExpressionName is a const
        // but it would work if you declared a *new* variable,
        // which has a different lexical binding
        console.log(functionExpressionName) // function
      };
      return functionExpressionName; 
    })();
    
    functionVariable();
    

    This isn't exactly what happens, but it's pretty close.