JavaScript variable declaration learning notes

Source: Internet
Author: User
Tags define function variable scope

Variable creation in js is usually called a "Declaration" variable. Next I will introduce some basic JavaScript variable declaration and usage methods. I hope this tutorial will be helpful to you.

Variable Declaration

JavaScript uses the keyword var to declare variables. You can declare the variables first and assign values, or assign values at the same time. Multiple variables are declared at the same time and separated by commas. For example:

The Code is as follows: Copy code
// Declare first and assign values later
Var sex;
Sex = "male ";
// Assign values while declaring
Var age = 22;
Var name = "James ";
// Declare multiple variables at the same time
Var x = 1, y = 2, z = 3;

// Separate multiple variables with commas (,). sex, age, name... called variable name, "male", 22, "Zhang San... it is called a variable value.

JavaScript is a weak language. When declaring a variable, you do not need to declare the data type. JavaScript automatically determines the data type based on the variable content.

JavaScript variable naming rules: variables must start with letters, $, and _ and cannot start with numbers or other characters.

Note: JavaScript is case sensitive. The variable age is not equal to AGE.

Use of Variables

After the variable is declared, you can use it.

For example, two variables x and y are declared:

The Code is as follows: Copy code

Var x = 2;
Var y = 3; to get the value of x + y, you can:
Var z = x + y;
Document. write (z); run the code and output 5.


Y:
 
Unassigned variable
An unassigned variable is a variable that has been declared with the var keyword but has not been assigned a value.

In JavaScript, unassigned variables have a default value: undefined, that is, "undefined".

For example:

The Code is as follows: Copy code

Var x; // x = undefined
Alert (x );

Run the code. A warning box is displayed, indicating undefined.

Note: unassigned variables are not declared variables. In JavaScript, when an unassigned variable is referenced and its value is undefined, an error is thrown when an undeclared variable is referenced.

For example:

The Code is as follows: Copy code

Alert (xyz );

Run the code without a warning box. Open Chrome debugging tool (F12) and you can see that the following error is thrown:

Uncaught ReferenceError: xyz is not defined

That is, "uncaptured reference error: xyz is not defined ".


At this time, someone may ask, what is the difference between the two declarations, and why there are these two different declaration methods, which involves the scope of variables in javascript. In javascript, the scope of a variable includes global and function-level.

Global variables can be declared in the external body of the function. No matter which method described above is used, the variables declared in the external body of the function are global variables. For example:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Var v = 1;

Function foo ()
{
Alert (v );
}

W = 2;
Function bar ()
{
Alert (w );
}

Foo ();
</Script>

Running result: 1 2

In addition, if the var keyword is not used, the declared variable is also a global variable. For example:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Function foo ()
{
V = 1;
}

Foo ();
Alert (v );
</Script>

Running result: 1
However, in this case, to use a variable, you must first call the function that declares the variable to initialize the variable, such as foo (). Otherwise, the error "variable v undefined" will occur.

Global variables exist as the properties of the window object because they can be accessed through window. $ ($ indicates the variable name. Of course, you can also directly access it using the variable name. The following describes why these two access methods are available.

Variables declared through the var keyword in a function are function-level variables, and their scope is limited only within the function. For example:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Function foo ()
{
Var v = 1;
Alert (v );
}

Alert (v );
</Script>

Running result: 1 variable "v" is not defined

Through the above analysis, we can find that the keyword var is mainly used to define function-level variables.

A careful friend may ask, if the same variable is defined inside and outside the function, what kind of result will it be? For example:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Var v = 1;
Function foo ()
{
Alert (v );
Var v = 2;
}

Foo ();
</Script>

Running result: undefined
!!!!! Some people may be depressed. v clearly defines the function foo () in vitro. Why is it undefined? This involves parsing javascript. Based on experience, the parsing process of javascript variables in the function body is:
Search for all var keywords, place the variable declaration at the beginning of the function body, and keep the value assignment and usage unchanged. In this way, the above javascript is actually equivalent:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Var v = 1;
Function foo ()
{
Var v;
Alert (v );
V = 2;
}

Foo ();
</Script>

According to this analysis, the above results are obvious, because the priority of the variables in the function is higher than that of the global variables (this is the case in most programming languages ), the variable v in the function overwrites the global variable v, but the result is undefined because it is declared but not assigned a value when the variable v in the function is used.

If you still need to use the defined global variable v in the method body, the window object is very useful at this time and can be accessed through window. v. For example:

The Code is as follows: Copy code

<Script type = "text/javascript" language = "javascript">
Var v = 1;
Function foo ()
{
Alert (window. v );
Alert (v );
Var v = 2;
}

Foo ();
</Script>

Running result: 2 undefined


Variable Scope

In JS, the scope of variables is divided into global variables and local variables. defined in the function is called local variables, and outside the function is called global variables. ("Global variables outside the function" is relative, and the premise discussed here is to use the variables explicitly declared by var. The variables not defined by var in the function are global variables by default, of course, ignoring var declaration variables is not in favor ).

The Code is as follows: Copy code

Var glob = 4; // declare a global variable outside the Function
Function fun (){
Var height = 20; // The local variable declared with var in the function
Weight = 50; // global variables are declared without var in the function
}
Fun ();
Alert (weight );

JS does not have block-level scope, that is, it is included in braces. In Java. Write the following code in the main method:

The Code is as follows: Copy code

Public static void main (String... args ){
For (int I = 0; I <5; I ++ ){
}
{
Int j = 10;
}
Int z = 20;
System. out. println (I); // I is invisible, and an error is reported during syntax analysis, that is, the compilation fails.
System. out. println (j); // j is invisible, and an error is reported during syntax analysis, that is, compilation fails.
System. out. println (z); // visible to z, output 20
}

However, in JS:

The Code is as follows: Copy code

For (var I = 0; I <5; I ++ ){
}
Var obj = {name: "Lily "};
For (var attr in obj ){
}
{
Var j = 10;
}
Alert (I); // output 4, no block-level scope
Alert (attr); // output name, no block-level scope
Alert (j); // output 10, no block-level scope

This also indicates a problem to avoid using the for Loop in a global scope and declaring variables at the same time. Otherwise, the global naming range will be contaminated.
Of course, the let keyword declaration variable (see the https://developer.mozilla.org/cn/New_in_JavaScript_1.7) in JS1.7 only applies to the for statement range.

The Code is as follows: Copy code

For (let I = 0; I <5; I ++ ){
// Todo
}
Alert (I); // an error is reported during running, prompting that I is undefined.

JS1.7 needs to reference <script type = "application/javascript; version = 1.7"/> </script>
Ps: firefox2 + implements JS1.7

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.