JavaScript uses function statements and expressions to define the difference between functions _javascript tips

Source: Internet
Author: User
Tags function definition

Using JavaScript for many years, wrote countless functions, today but really understand the difference between the definitions of the two functions, is really a tragedy, write down this essay, to remind themselves to lay a good foundation, a lot of age, can not continue to be ignorant.

Usually we see the following two ways to define a function:

Copy Code code as follows:

Function statement
function fn (str)
{
Console.log (str);
};

An expression definition
var fnx=function (str)
{
Console.log (str+ ' from Fnx ');
};


Used to be the feeling of their own fingers to use both-_-| | , today read the JS Foundation, finally solved the hearts of their confusion:

A new function object is created in both ways, but a function declaration statement has a function name that is a variable name, a variable to a function object, and, as with VAR declaration variables, functions in a function definition statement are displayed in advance to the top of the script or function, so they are visible throughout the script and function, but using the Var Expression definition function, only the variable declaration is advanced, the variable initialization code is still in the original position, functions created with Function statement, function name and function body are all advanced, so we can use it before declaring it.

The code example is as follows:

Copy Code code as follows:

Console.log (FN) (typeof); function
FN (' abc '); Abc


Console.log (typeof (FNX)); Undefined

if (FNX)
FNX (' abc '); Would not execute
Else
Console.log (' fnx is undefined '); FNX is undefined

Function statement
function fn (str)
{
Console.log (str);
};

An expression definition
var fnx=function (str)
{
Console.log (str+ ' from Fnx ');
};


The code is very simple, hope and I did not understand the difference between the two students can gain.

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.