JS local variables and global variables

Source: Internet
Author: User

In the outermost definition is the global variable

If you do not use VAR to declare directly assigned variables inside a function, then this variable is also a global variable

Variables declared with Var inside a function are called local variables

Defined at the beginning of the global variable in the entire JS range can be accessed, can be used, defined in the indefinite position of the global variable, only after the definition of variables to use the variable, if a variable is defined in a function, and declared with Var, it is a local variable, only valid in the method body, parameters are local variables , in the method body, can not be accessed, if the variable is assigned directly in the body of the method, without Var declaration, it is a global variable, but only after the function is executed to be externally accessible, if not executed, this variable can still access the

The return value of a function can be used as a parameter to another function, so that the callback function

<script>window.onload=function () {var y=1;//belongs to the global variable function show (x) {var num=2;sum=3;return num*x;} Show ();//alert (num); error, the scope of NUM is limited to method body//alert (x), an error occurs, the function of parameter A is limited to the method body alert (sum),//Popup sum value, method body without var declaration of variables, Not only in the body of the method, it is equivalent to a global variable (note that it is only accessible after the method has been run, otherwise it will prompt the sum is not defined) function fun () {return 5;} Alert (Fun ()));//This is a callback function, which is the way the return value of one function is evaluated directly as a parameter of another function}</script>

JS local variables and global variables

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.