JavaScript exploration: function declaration and function expression

Source: Internet
Author: User
In ECMAScript, the two most common methods for creating a function are function expressions and function declarations.

In ECMAScript, the two most common methods for creating a function are function expressions and function declarations. The difference between the two methods is a bit dizzy, because the ECMA specification only makes it clear: the function declaration must contain an Identifier (the name of a function that is commonly used), while the function expression can omit this Identifier:

Function declaration:

Function Name (parameter: OPTIONAL) {function body}

Function expression:

Function Name (optional) (parameter: OPTIONAL) {function body}

Therefore, we can see that if the function name is not declared, it must be an expression. If the function name is declared, how can we determine whether it is a function declaration or a function expression? ECMAScript is distinguished by context. If function foo () {} is a part of the value assignment expression, it is a function expression. If function foo () {} is contained in a function, or at the top of the program, it is a function declaration.

Function foo () {}// declaration, because it is part of the program var bar = function foo () {}; // expression, because it is a part of the value assignment expression new function bar () {}; // expression, because it is a new expression (function () {function bar () {}// declaration, because it is part of the function body })();

Another function expression is not very common, that is, function foo () {}) enclosed by brackets. It is the reason for the expression because parentheses () are a grouping operator, it can only contain expressions. Let's look at several examples:

Function foo () {}// function declaration (function foo () {}); // function expression: include in the grouping operator try {(var x = 5 ); // grouping operator, which can only contain expressions but not statements: the var here is the statement} catch (err) {// SyntaxError}

You can think that when using eval to execute JSON, The JSON string is usually included in a parentheses: eval ('+ json + ')'), the reason for doing so is that the grouping operator, that is, this pair of parentheses, will force the parser to parse the JSON curly braces into expressions rather than code blocks.

Try {"x": 5}; // "{" and "}" are parsed into code blocks} catch (err) {// SyntaxError} ({"x ": 5}); // The grouping operator forcibly parses "{" and "}" as the object literal.

There are very subtle differences between expressions and declarations. First, the function declaration will be parsed and evaluated before any expression is parsed and evaluated, even if your declaration is on the last line of the Code, it will also be parsed/evaluated before the first expression in the same scope. For example, the fn function is declared after alert, but when alert is executed, fn has been defined:

alert(fn());function fn() {return 'Hello world!';}

In addition, you need to note that function declaration can be used in conditional statements but is not standardized. That is to say, different environments may have different execution results. In this case, it is best to use a function expression:

// Never do this! // Some browsers return the first function, while some browsers return the second if (true) {function foo () {return 'first ';}} else {function foo () {return 'second';} foo (); // opposite. In this case, we use the function expression var foo; if (true) {foo = function () {return 'first ';};} else {foo = function () {return 'second' ;};} foo ();

The actual rules of the function declaration are as follows:

Function declarations can only appear in programs or functions. Syntactically, they cannot appear in blocks (blocks) ({...}). for example, they cannot appear in if, while, or for statements. Because the Block can only contain Statement statements, but cannot contain source elements such as function declaration. On the other hand, if you take a closer look at the rule, you will also find that the only possible reason for the expression to appear in the Block is to make it part of the expression statement. However, the specification clearly stipulates that expression statements cannot start with a function keyword. In fact, function expressions cannot appear in Statement statements or blocks (because blocks are composed of Statement statements ).

Additional reading

The topic list of this article is as follows:

  1. How should we understand the working principle of the JavaScript engine?
  2. JavaScript exploration: the importance of writing maintainable code
  3. JavaScript exploration: exercise caution when using global variables
  4. JavaScript exploration: var pre-parsing and side effects
  5. JavaScript exploration: for Loop (for Loops)
  6. JavaScript exploration: for-in loop (for-in Loops)
  7. Exploring JavaScript: Prototypes is too powerful
  8. JavaScript: eval () is the devil"
  9. JavaScript exploration: Using parseInt () for Numerical Conversion
  10. Exploring JavaScript: Basic coding specifications
  11. JavaScript exploration: function declaration and function expression
  12. JavaScript exploration: Name function expressions
  13. JavaScript: function name in the debugger
  14. JavaScript: JScript Bug
  15. JavaScript exploration: Memory Management of JScript
  16. Exploring JavaScript: SpiderMonkey's quirks
  17. JavaScript exploration: an alternative solution to naming function expressions
  18. JavaScript exploration: Object
  19. JavaScript exploration: Prototype chain
  20. JavaScript exploration: Constructor
  21. JavaScript probing: executable context Stack
  22. Execution context 1: Variable object and activity object
  23. Execution context 2: Scope chain Scope Chains
  24. Execution context 3: Closure Closures
  25. Execution context 4: This pointer
  26. Exploring JavaScript: Powerful prototype and prototype chain
  27. JavaScript Functions 1: function declaration
  28. JavaScript function 2: function expressions
  29. JavaScript function 3: function expressions in a group
  30. JavaScript function 4: function Constructor
  31. JavaScript variable object 1: VO Declaration
  32. JavaScript variable object 2: VO in different execution contexts
  33. JavaScript variable object 3: two stages of execution Context
  34. JavaScript variable object IV: Variables
  35. Property of the JavaScript variable object __parent _
  36. JavaScript scope chain 1: Scope chain Definition
  37. JavaScript scope chain 2: function Lifecycle
  38. JavaScript scope chain 3: Scope chain features
  39. JavaScript closure 1: Introduction to closures
  40. JavaScript closure 2: Implementation of closure
  41. JavaScript closure 3: Closure usage

This article is available at http://www.nowamagic.net/librarys/veda/detail/1630.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.