javascriptfunctionjavascript-function-declaration

Does assigning to a function overwrite the function or create an implicit global?


In JavaScript we can declare a function and then assign to it, as follows:

function spam() { return "spam 'n eggs"; }
spam = spam();
spam(); // TypeError: spam is not a function.

Does this code change the value of a global variable called spam, or create an implicit global variable that shadows the function spam?


Solution

  • It doesn't overwrite the function, but it does assign a string to that variable. The function defined on the first line returns a string, and because the second line sets spam equal to the return value (since the function is called (notice the parentheses)) spam then is a string.

    Try this in the browser console: window.spam. After the first line, it should reveal that function. Then after the second line it should show that string.

    function spam() {
      return "spam 'n eggs";
    }
    console.log('typeof spam: ',typeof spam, 'typeof window.spam: ',typeof window.spam);
    spam = spam(); //spam is assigned a string
    console.log('typeof spam: ',typeof spam, 'typeof window.spam: ',typeof window.spam);
    spam(); // TypeError: spam is not a function.

    if we moved that code inside a function, the var keyword could be used for local scope:

    function assignSpam() {
            var spam = function() { return "spam 'n eggs"; }
            console.log('typeof spam after initial assignment: ',typeof spam);
            spam = spam(); //spam is assigned a string
            console.log('typeof spam after assigning to spam(): ',typeof spam);
            spam(); // TypeError: spam is not a function.
        }
        assignSpam();
        spam; //undefined

    Results should be similar in server-side javascript (e.g. NodeJS).