Introduction to the difference between javascript function declarations and function expressions

  • 2020-03-26 21:23:05
  • OfStack

Again, first on the code:
var f = function g() { 
return 1; 
if (false) { 
f = function g(){ 
return 2; 
alert(g()); // 2 

Throwing this code into IE 6 is completely different from throwing it into chrome.

Here output 2 is the effect inside ie6, if in chorme will appear g is not defined.

This is a JScript bug.

It's pretty clear here that this is just a function of g. Included in the if conditional statement is only the definition of the function expression, not the declaration of the function.

Then this direct access is bound to be wrong.

So what are declarations, what are functional expressions?

In ECMAScript, the two most common methods for creating functions are function expressions and function declarations. The difference between the two is a bit confusing, because the ECMA specification states only that a function declaration must have an Identifier (that is, the name of a function), while a function expression can omit this Identifier:
Function declaration:
Function name (parameter: optional){function body}
Function expression:
Function name (optional) (parameter: optional){function body}

So, you can see that if you don't declare a function name, it must be an expression, but if you declare a function name, how do you determine whether it's a function declaration or a function expression? ECMAScript is context-sensitive; if function foo(){} is part of an assignment, it is a function expression; if function foo(){} is included in a function or at the top of the program, it is a function declaration.

A less common type of function expression is enclosed in parentheses (function foo(){}), which is an expression because the parentheses () is a grouping operator that can only contain expressions inside.

As you might expect, when you execute JSON with eval, the JSON string is usually enclosed in a single parentheses: eval('(' + JSON + ')'), because the grouping operator, the pair of parentheses, forces the parser to parse the JSON curly braces into an expression rather than a block of code.

Related articles: