Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can functions be defined

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

This:

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

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

Why?

like image 715
theonlygusti Avatar asked Dec 07 '22 13:12

theonlygusti


1 Answers

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.

like image 175
Nurbol Alpysbayev Avatar answered Dec 10 '22 02:12

Nurbol Alpysbayev