1

So I found this terminology a little bit confusing. I normally see tutorials talking about function expression with an variable assigned to a function, but also, from Mozilla's official website function expression, it says:

A function expression is very similar to and has almost the same syntax as a function statement (see function statement for details). The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as a IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.

so it doesn't mention anything about variable assignation. So, is

var funcvar = function(){};

or

function(){};

is a function expression? Or neither of them? Can anybody give me a concise definition?

Thanks guys!

EDIT: or, is

function(){};

called function statement? And it's an anonymous function?

Hang Chen
  • 549
  • 1
  • 7
  • 18
  • 1
    In your `var funcvar = function(){};`, `function(){}` is the function expression. *"or, is...called function statement"* No, it's a function expression. *"And it's an anonymous function?"* The *expression* is anonymous. Whether the function is anonymous depends on where the expression is. For instance, in your `var funcvar = function(){};`, although the expression is an anonymous function expression, the function isn't anonymous (in ES2015+). It has the name `funcvar`, inferred from the assignment expression. – T.J. Crowder Dec 31 '17 at 12:07
  • Thanks @T.J.Crowder! I've seen your provided post as well. Then if we write it without a var assignation, `function(){}`; itself becomes a function declaration? – Hang Chen Dec 31 '17 at 12:09
  • See that post for the details, but yes, if it were standalone, that would be a function declaration except that function declarations require an explicit name (e.g., `function foo() { }`, not `function() { }`). – T.J. Crowder Dec 31 '17 at 12:10
  • 1
    Thanks, I've read through it, and I think I got it now. Thanks for your help! @T.J.Crowder – Hang Chen Dec 31 '17 at 12:12
  • Just to round this out: JavaScript doesn't have a function *statement* at all, just expressions and declarations. But as of ES2015, function declarations can be used within blocks, which makes them really quite statement-like (but still not statements, they still have effects on the scope prior to where they appear). – T.J. Crowder Dec 31 '17 at 12:13

0 Answers0