JavaScript variable declaration and function declaration promotion

Source: Internet
Author: User

In JavaScript, a variable or function is used before declaring a variable or function, which creates an error. These will appear in many JS written questions.

First look at the following question:

1(function( ) {2      varx =foo ();3      varFoo =functionfoo () {4            return"Foobar";5      } 6      returnx;7})( );
Q: The return value of the above function is ()

A, type Error
B, Foobar
C, undefined
D, foo ()
the answer should be a, not d. For that reason, we should all know. The problem is in this code:
var foo = function foo () {
return "Foobar";
}
Declaring the variable Foo with VAR will raise it to the front of the function body, but the function expression will not be promoted as follows:
var foo;
var x = foo ();
foo = function foo () {...};
Therefore, when the function executes to var x = foo (), the function foo () has not been declared, and therefore the type error occurs: Typeerror:foo is not a function.

There are two ways to solve the above code problem:
1.
(function() {
function foo () {
Return "Foobar"

var x = foo ();
Return
})( );

2, remove the Var foo, directly using function () to declare foo (), so that Foo () will also be promoted to the front

1 (function() {2      var x = foo (); 3      function  foo () {4            return "Foobar" ;5      6      return7}) ( );

JavaScript variable declaration and function declaration promotion

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.