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?
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
spamequal 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.if we moved that code inside a function, the var keyword could be used for local scope:
Results should be similar in server-side javascript (e.g. NodeJS).