Differences between defining functions using function statements and expressions in javascript

Source: Internet
Author: User

I have been using javascript for many years and have written countless functions, but today I have really understood the differences between the two function definitions. It is really a tragedy. I wrote this article to remind myself to lay a solid foundation at all times, you are too old to be ignorant.

We usually see the following two methods to define functions:
Copy codeThe Code is as follows:
// Function statement
Function fn (str)
{
Console. log (str );
};

// Expression Definition
Var fnx = function (str)
{
Console. log (str + 'from fnx ');
};

In the past, I used to use both-_-| as I felt by my fingers. Today I read the js basics and finally solved their confusion:

Both methods create a new function object, but the function name of the function declaration statement is a variable name. The variable points to the function object, just like declaring a variable through var, the functions in the Function Definition Statement are displayed at the top of the script or function, so they are visible throughout the script and function, but the var expression is used to define the function, only when the variable declaration is in advance, the variable initialization code is still in the original position. functions created using function statements, function names, and function bodies are both in advance, so we can use it before declaring it.

The code example is as follows:
Copy codeThe Code is as follows:
Console. log (typeof (fn); // function
Fn ('abc'); // abc


Console. log (typeof (fnx); // undefined

If (fnx)
Fnx ('abc'); // will not execute
Else
Console. log ('fnx is undefined'); // fnx is undefined

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

// Expression Definition
Var fnx = function (str)
{
Console. log (str + 'from fnx ');
};

The code is very simple. I hope that you will be able to get something better if you don't understand the difference between the two.

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.