Reputation: 916
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?
Upvotes: 0
Views: 39
Reputation: 8297
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).
Upvotes: 1
Reputation: 147513
Does this code overwrite the function held by a global variable called spam,
No. The initial value assigned to spam is a reference to the function. Assigning a new value doesn't alter the function, it just assigns a new value to spam.
E.g.
function spam(){return 'I am spam';}
var b = spam;
spam = spam();
console.log(spam) // 'I am spam'
console.log(b); // Original "spam" function
console.log(b()); // 'I am spam'
or create an implicit global variable that shadows the function spam?
It just assigns a new value to spam. The original function object still exists, though if there are no other references to it, it is available for garbage collection.
Upvotes: 1