JavaScript basic syntax--variables and identifiers

Source: Internet
Author: User
Tags naming convention variable scope

Show Table of ContentsDirectory[1] definition [2] naming convention [3] declaration [4] attribute [5] scope [6] Declaration elevation [7] Property variablePrevious words

With regard to JavaScript, the first important concept is variable, and the working mechanism of the variable is the basic feature of JavaScript. In fact, a variable is one of the identifiers. This article describes the variables and identifiers in detail

Defined

An identifier (Identifier) is a name used to name a variable, function, property, parameter, or as a marker for a jump position in some loop statement

//Variablevar Identifier =123;//new Object). Identifier =  "test" ; // functions and parameters function IdentifierName (Identifier1) {}; //jump  tagged identifier:for (var i = 0; i < 5; I++) {if (i = = 3break Identifier;}}     

In daily life, some things are fixed and some things change. For example, a person's name and birthday are fixed, but the mood and age change over time. People call things that change, they're variables.

The program assigns a value to a variable when it needs to save it for future use. A variable (variable) is a placeholder for holding a value, and a reference to a value can be obtained by the variable name

Naming rules

In the lexical structure article, we introduce JavaScript as a case-sensitive language, and like any other programming language, JavaScript retains some identifiers for its own use, and reserved words cannot be used as ordinary identifiers

[note] reserved words include keywords, future reserved words, empty literals, and Boolean literals

Reserved word reservedword::   Keyword   futurereservedword   nullliteral   booleanliteral

In addition, JavaScript pre-defines many global variables and functions, and should avoid having their names used as identifier names.

Arguments Array Boolean Date decodeuri decodeuricomponent encodeuriencodeuricomponent Error eval evalerror Function Infin ity Isfiniteisnan JSON Math NaN number Object parsefloat parseint rangeerrorreferenceerror RegExp String syntaxerror Typee Rror undefined Urierror

JavaScript identifier names allow letters, numbers, dollar signs, and underscores (but the first character is not allowed to be a number)

Error demonstration  6num  // Beginning cannot be used with numbers////in   The middle cannot use except for (_ $) special symbols, such as (% +/etc)    

JavaScript allows letters and numbers in the Embox set of Unicode characters (including Chinese) to appear in the identifier. Therefore, programmers can also use non-English language or mathematical symbols to write identifiers

var Test text = ' Test ';

[note] For portability and easy-to-write considerations, we don't usually use extended ASCII or Unicode characters

Usually the hump format is the preferred format for identifier naming, with the first letter lowercase, and the first letter of each remaining word capitalized

var mymoodtoday = ' happy ';

For different data types, JavaScript has a convention for naming names for identifiers

Type                    prefix            example        Array (arrays)     a    Aitems boolean (Boolean)   b    biscomplete Floating-point number (float)  F    Fprice function (function)   fn    fnhandler integer (int)   i    iitemcount Objects (object) 
    o    oDIv1 Regular expression (REGEXP)        re    Reemailcheck string (string)       s    susername variable (Var Iant)   V                    

Variable declaration

Statement

In JavaScript, you should declare (declare) before using a variable, which is declared using the keyword VAR (variable's abbreviation).

var i;  var sum; 

You can also declare multiple variables with a var keyword

var i, sum;

Assign value

The operation of storing a value in a variable is called an Assignment (Assignment). After a variable is assigned, we say that the variable contains the value

The process of assigning a value to a variable for the first time, called initialization

We can write the initial assignment and the variable declaration together.

'Hello';  var i=0,j=0,k=0;      

If the variable is not given an initial value in the Var declaration statement, then the variable is declared, but before it is saved to a value, its initial value is undefined

You can also use the VAR statement in the For loop and the for-in loop, which makes it more concise to declare the loop variable used in the loop syntax

for (var i=0; i<; i++) Console.log (i);  

Variables can be assigned at the time of declaration, but cannot have other actions, such as + =,-=, etc.

var a = 2; // is the correct var a + = 2;  is the wrong var a = 2++;  is wrong, + + can only be used for variables and cannot be used for constants       

Duplicate declaration

Repeating a variable with a VAR statement is legal and harmless, and is equivalent to a re-assignment if it is repeatedly declared with an assignment operation

Omission statement

If you attempt to read the value of a variable that is not declared, JavaScript will error

JavaScript allows the omission of a declaration that assigns a value directly to a variable without prior declaration, and the assignment automatically declares the variable however, in ECMAScript5 strict mode, assigning a value to an undeclared variable will cause an error.
<script>' usestrict'5; Console.log (a);  </Script>         
Variable Properties

JavaScript variables are weakly typed (also called loosely typed), and so-called loose types can be used to hold any type of data

There are two types of programming languages: Dynamic type language and static type language. Dynamic type language refers to the language of data type checking during run time, that is, when programming in a dynamic type language, you do not have to specify a data type for any variable, and the language will record the data type internally when it is assigned to the variable for the first time. JavaScript is the representative of a dynamic type language.

In JavaScript, you can modify the type of a value while modifying the value of a variable

var message = ' Hi ';  valid, but not recommended  

The characteristics of loosely typed variables are summed up with two points: one is not to specify the data type of the variable when declaring, and the other is to modify the data type when assigning the value.

Variable scope

The scope of the variable (scope), also known as the Execution Environment (execution context), is the area in the program source code that defines the variable.

Scope is divided into global scope and function scope (also called local scope) two kinds of

The global scope is one of the outermost execution environments in which the global execution environment is considered a Window object. All global variables and functions are created as properties and methods of the Window object. Global variables have global scope and are defined everywhere in the JavaScript code. Global scope is not destroyed until an application exits, such as closing a Web page or browser

Variables declared within a function are defined only within the body of the function. They are local variables and the scope is local. Function parameters are also local variables, and they are defined only within the function body. After all code in the function scope is executed, the scope is destroyed, and all the variables and function definitions stored therein are destroyed.

function Test () {    var message  = ' Hi ';} Test (); alert (message); // error    

If you omit the var operator, a global variable is created

function Test () {    message  = ' Hi ';} Test (); alert (message); //' Hi '   

Although omitting the var operator can define global variables, it is not recommended. Global variables defined in local scopes are difficult to maintain, and if the Var operator is deliberately ignored, it can cause unnecessary confusion due to the fact that the variable is not immediately defined, and assigning a value to an undeclared variable in strict mode causes the Referenceerror error to be thrown

In the body of a function, a local variable takes precedence over a global variable of the same name, and if a local variable or function parameter declared within a function has the same names as a variable and a global variable, then the global variable is obscured by the local variable.

var scope = ' global ';  function Checkscope () {    var scope = ' Local 'return scope;}; Checkscope (); //' local '       

Declaration elevation (hoisting)

Block-level scopes

A block-level scope is where each piece of code within the curly braces has its own scope, and JavaScript does not have a block-level scope. JavaScript has only function scopes: variables are defined in the body of the function that declares them, and in any function within which the body of the function is nested.

This means that the variable is even available before the declaration. This feature of JavaScript is informally referred to as declaration elevation (hoisting), and all variables declared in JavaScript functions (not involving assignments) are advanced to the top of the function body

[note] In addition to the variable promotion, the function is also promoted, to the function section will be described in detail

var scope = ' global ';  function F () {    console.log (scope);  var scope = ' local '; Console.log (scope);  ' Local '}       
after the variable declaration is promoted, it is equivalent to the following code var scope = ' global ';  functionvar scope; Console.log (scope);  undefined scope = ' local '; Console.log (scope);  ' Local '}          

There is no block-level scope in JavaScript, so some programmers deliberately place variable declarations on top of the function body, a source code that clearly reflects the real variable scope

Property variables

When declaring a JavaScript global variable, you are actually defining a property of the Global object window

When declaring a variable with VAR, the variable created is not configurable, meaning that the variable cannot be deleted by the delete operator

var truevar = 1; Console.log (Truevar,window.truevar);  1 1delete truevar;  Falseconsole.log (Truevar,window.truevar); //1 1       

If you do not use strict mode and assign a value to an undeclared variable, JavaScript automatically creates a global variable that is the normal configurable property of the global object and can be deleted.

WINDOW.FAKEVAR1 = 10; Console.log (FAKEVAR1,WINDOW.FAKEVAR1);//10 10THIS.FAKEVAR2 = 20; Console.log (FAKEVAR2,WINDOW.FAKEVAR2);//20fakevar = 30;console.log (Fakevar,window.fakevar); //30 30delete WINDOW.FAKEVAR1; //truedelete THIS.FAKEVAR2; //truedelete fakevar;< Span style= "COLOR: #008000" >//trueconsole.log (fakevar1 , WINDOW.FAKEVAR1); // error Console.log (FAKEVAR2,WINDOW.FAKEVAR2); // error Console.log (Fakevar,window.fakevar); // error         
Reprinted from:: http://www.cnblogs.com/xiaohuochai/

The JavaScript global variable is a property of the global object, which is mandated in ECMAScript. A local variable is treated as a property of an object associated with a function call. ECMASCRIPT3 is called the Call object, ECMASCRIPT5 is called the Declaration context object (declarative environment record). JavaScript allows you to refer to global objects using the This keyword, but there is no way to refer to objects stored in local variables. This unique property of storing local variable objects is an internal implementation that is invisible to us

JavaScript basic syntax--variables and identifiers

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.