I read lots of pages on this argument, but still can't understand why this (declaration)
function foo() {console.log("foo");}
(function(){
// Really there is nothing here
})();
doesn't do anything, while this (expression)
var foo = function() {console.log("foo");}
(function(){
// Really there is nothing here
})();
outputs
foo
Uncaught TypeError: undefined is not a function
What's going or here?
2 Answers 2
You are missing the semicolon after the assignment, as Felix Kling pointed out.
The parenthesis around the second anonymous function will be interpreted as the parentheses around the parameters for a function call:
var foo = function() {console.log("foo");}(function(){ })();
The expression function() {console.log("foo");}(function(){ }) will return undefined as there is no return statement in the first function. The last pair of parentheses will make it another function call, but as undefined is not a function, you get that specific error message.
1 Comment
gotchas of javascriptThis is a case why semi colons should NOT be optional. Whitespace is just there to make it easier for us to read. The code:
var foo = function() {console.log("foo");}
(function(){
// Really there is nothing here
})();
looks like this
var foo = function() {console.log("foo");}(function(){})();
making it look like a named function call
myFunction(function(){})();
or
myFunction("some code")();
The first function myFunction("some code") returns undefined and than you try to run that function.
~undefined~();
So with the return in there.
var foo = function() {console.log("foo"); return undefined;}(function(){})();
The code would run fine if you returned a function
var foo = function() {console.log("foo"); return arguments[0];}(function(){return "hello"})();
var foo = function() {console.log("foo");};. I'm quite certain this is a duplicate, will try to find it...console.log("foo");in the first function. It's called directly, not assigned to the variable. The result of the calls would be assigned to the variable.