The difference between a JavaScript function declaration and a function expression

Source: Internet
Author: User

There are several ways to define a function, the most common being the function declaration and the function expression, although you can implement the definition function, but there is a difference between them.

1. For example:

1.1 Function declarations

function log () {
Console.log.apply (console, arguments);
}

Log is the function name that points to the function object it declares.

1.2 Function expressions

var function () {      console.log.apply (console, arguments);};

Log also points to the function object it declares, but as a variable.

1.3 from the subsequent call, they can all achieve the same effect, no difference. But maybe you accidentally called before the function definition, and the difference came.

1.3.1 is called after the function definition, the effect is the same.

function log () {      console.log.apply (console, arguments);} var function () {      console.log.apply (console, arguments);}; Log (1); log2 (2);

1.3.2 called before the function definition, LOG2 calls an error.

Log (1); log2 (2); function log () {      console.log.apply (console, arguments);} var function () {      console.log.apply (console, arguments);};

1.3.3 The reason is that the parser reads the two definitions in a different order, the parser reads the function declaration in advance and makes it available before executing the subsequent code, whereas for a function expression, the parser executes only when it reads the line where the function expression is located, simple, like this:

var a = b; var b=0; Console.log (a);

At this point, log out of a is undefined, at the time of assignment A, the parser does not read to B.

The difference between a JavaScript function declaration and a function expression

Related Article

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.