Javascrippt scope-function scope and declaration advanced "from the Javascript authoritative guide"

Source: Internet
Author: User

The scope of a variable is the area in the program's source code that defines the variable. Global Variables have global scope and are defined everywhere in the JavaScript code.

However, variables declared within a function are defined only within the function body. They are local variables and the scope is local. Function parameters are also local variables, they are defined only in the body.

in the body of a function, a local variable takes precedence over a global variable of the same name. If a local variable or function parameter declared within a function has the same name as a variable and a global variable,

The global is covered by local variables .

eg

var a= "AAAA";

(function () {
var a= "BBB";
Console.log (a);

})();

= Output bbbb;


In a generic programming language, each piece of code within the curly braces has its own scope, and the variables are not visible outside the code snippet that declares them. We call this block-level scope.
In JavaScript, however, there is no block-level scope. Instead, the function scope is used: variables are visible in the body of any function that declares their function body and the function's nesting the .

eg

(function test (O) {
var i=0;

if (typeof O = = "Object") {

var j=0;

for (var k=0; k<10;k++) {
Console.log (k); = 0~9

}

Console.log (k); =>10

}

Console.log (j);=> 0

})({});

The above example shows that the variables declared in the function body are always visible within the function body. This also means that the variable is even available before the declaration, which has an informal called function Variable declaration in advance

Javascrippt scope-function scope and declaration advanced "from the Javascript authoritative guide"

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.