Where can functions be defined

  • A+

Edited: The expression function foo() {return 20;}, foo() was meant to be a single argument to console.log).


console.log((function foo() {return 20;}, foo()));

Doesn't work, I get ReferenceError because foo has not been defined.



console.log(function foo() {return 20;}, foo()); 

In this code, you are passing a named (foo) function as an argument to console.log. Got it? You've never declared function foo, you're just passing it as an argument. In javascript a function declaration and a function expression has the same syntax hence the confusion.

That said, passing a named (instead of anonymous) function is almost always useless. Your code is equivalent to this:

console.log(function () {return 20;}, foo()); 

where function () {return 20;} is an anonymous function in contrast to a named one. And anonymous functions are very wide-spread in JS, because again, names in named function expressions are mostly useless.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: