Basic javascript syntax-fully understand variables, identifiers, and javascript Variables
The first important concept about javascript is variables. The working mechanism of variables is the basic feature of javascript. In fact, a variable is a type of identifier. This document describes variables and identifiers in detail.
Definition
Identifier is a name used to name variables, functions, attributes, and parameters, or to mark the jump position in some loop statements.
// Variable var Identifier = 123; // attribute (new Object ). identifier = 'test'; // function and Parameter function IdentifierName (Identifier1) {}; // jump tag Identifier: for (var I = 0; I <5; I ++) {if (I = 3) {break Identifier ;}}
In daily life, some things are fixed and some things change. For example, the name and birthday of a person are fixed, but the mood and age change with time. People call those things that will change as variables.
When the program needs to save the value for future use, it will assign it to a variable. A variable is a placeholder for storing values. You can use the variable name to obtain reference to the value.
Naming rules
In the lexical structure article, we introduced that javascript is a case-sensitive language, and like any other programming language, javascript retains some identifiers for its own use, reserved Words cannot be used as common identifiers
[Note] reserved words include keywords, future reserved words, empty words, and Boolean words
Reserved word ReservedWord: Keyword FutureReservedWord NullLiteral BooleanLiteral
Javascript identifier names can contain letters, numbers, dollar signs, and underscores (but the first character is not allowed to be numbers)
// Error example 6num // cannot start with a Number % sum // cannot start with a special symbol except (_ $), such as (% +) except (_ $) and other special characters, such as (% +/), cannot start with sum + num)
Javascript allows the identifier to contain letters and numbers (including Chinese) in the full set of Unicode characters ). Therefore, programmers can use non-English or mathematical symbols to write identifiers.
Var test text = 'test ';
[Note] for portability and ease of writing, we usually do not use extended ASCII or Unicode characters
Generally, the hump format is the preferred format for naming identifiers. The first letter is in lowercase, and the first letter of each remaining word is in uppercase.
var myMoodToday = 'happy';
For different data types, javascript has a naming convention for identifiers.
Type prefix example Array (Array) a aItems Boolean (Boolean) B bIsComplete floating point number (Float) f fPrice Function (Function) fn fnHandler Integer (Integer) I iItemCount Object (Object) o oDIv1 Regular Expression (RegExp) re reEmailCheck String (String) s sUserName variable () Variant v vAnything
Variable Declaration
Statement
In javascript, declare should be declared before a variable is used. The variable is declared using the keyword var (abbreviation of variable ).
var i;var sum;
You can also declare multiple variables using the var keyword.
var i ,sum;
Assignment
The operation to store values into variables is called assignment ). After a variable is assigned a value, we will say that the variable contains this value.
The process of assigning values to variables for the first time is called initialization.
We can combine the initial value assignment and variable declaration of a variable.
var message = 'hello';var i=0,j=0,k=0;
If the initial value is not specified for the variable in the var declaration statement, although this variable is declared, its initial value is undefined before it is saved to a value.
You can also use the var statement in the for loop and for-in loop, so that you can more concisely declare the loop variables used in the loop syntax.
for(var i=0; i<10; i++)console.log(i);
Variables can be assigned values during declaration, but other operations, such as + = and-=, are not allowed.
Var a = 2; // The correct var a + = 2; // The error var a = 2 ++; // The error is returned. ++ can only be used for variables, cannot be used as a constant
Repeated statement
It is legal and harmless to repeatedly declare a variable using the var statement. If the variable is repeatedly declared and has a value assignment operation, it is equivalent to re-assigning a value.
Omission statement
Javascript reports an error if you try to read the value of an undeclared variable.
Javascript allows omission Declaration, that is, assigning values to a variable without prior declaration. The assignment operation automatically declares the variable.
However, in the strict mode of ECMAScript5, an error is returned when you assign a value to an unspecified variable.
<script>'use strict';a = 5;console.log(a);</script>
Variable features
Javascript variables are of a weak type (also called a loose type). The loose type can be used to store any type of data.
Programming Languages: Dynamic Language and static language. A dynamic type language is a language that performs a data type check during running. That is to say, when programming in a dynamic type language, no data type is required for any variable, this language records the data type when it is assigned a variable for the first time. Javascript represents a dynamic language.
In javascript, you can modify the type of the value while modifying the variable value.
Var message = 'Hi'; message = 100; // valid, but not recommended
The features of variable loose types are summarized as follows: First, you do not need to specify the data type for the variable during Declaration; second, you can modify the data type when assigning values.
Variable Scope
The scope of a variable, also known as the execution context, is the region that defines this variable in the program source code.
There are two scopes: global scope and function scope (also called local scope ).
Global scope is a peripheral execution environment. In a web browser, 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 a global scope and are defined everywhere in javascript code. The global scope will not be destroyed until the application exits, for example, when the web page or browser is closed.
Variables declared in a function are defined only in the function body. They are local variables and scope is local. Function parameters are also local variables, which are defined only in the function body. After all code in the function scope is executed, the scope is destroyed, and all variables and function definitions stored in the scope are destroyed.
Function test () {var message = 'Hi';} test (); alert (message); // Error
If the var operator is omitted, a global variable is created.
function test(){ message = 'hi';}test();alert(message);//'hi'
Although the var operator can be omitted to define global variables, it is not recommended. It is difficult to maintain the global variables defined in the local scope. If the var operator is ignored intentionally, unnecessary confusion may occur because the corresponding variables are not immediately defined, assigning a value to an undeclared variable in strict mode will cause a ReferenceError.
In a function, the priority of local variables is higher than that of global variables with the same name, then the global variable is overwritten by the local variable.
var scope = 'global';function checkscope(){ var scope = 'local'; return scope;};checkscope();//'local'
Hoisting)
Block-level scope
Block-level scope means that each piece of code in curly brackets has its own scope, while javascript has no block-level scope. Javascript only has function scope: variables are defined in the declared function bodies and any function nested in this function body.
This means that the variable is even available before it is declared. The javascript feature is informal called hoisting. All variables declared in javascript Functions (not involving assignments) are pushed to the top of the function body.
[Note] in addition to variable elevation, functions are also upgraded. The function section will provide a detailed introduction.
var scope = 'global';function f(){ console.log(scope);//undefined var scope = 'local'; console.log(scope);//'local'}
// After the variable declaration is upgraded, it is equivalent to the following code var scope = 'global'; function f () {var scope; console. log (scope); // undefined scope = 'local'; console. log (scope); // 'local '}
Javascript does not have block-level scope, so some programmers place variable declarations on the top of the function body. This source code clearly reflects the real variable scope.
Attribute variable
When declaring a javascript global variable, it actually defines an attribute of the Global Object window.
When a variable is declared using var, the created variable cannot be configured, that is, the variable cannot be deleted through the delete operator.
var truevar = 1;console.log(truevar,window.truevar);//1 1delete truevar;//falseconsole.log(truevar,window.truevar);//1 1
If the strict mode is not used and an undeclared variable is assigned a value, javascript automatically creates a global variable. The variables created in this mode are normal configurable attributes of the global object, you can delete them.
Window. fakevar1 = 10; console. log (fakevar1, window. fakevar1); // 10 10 this. fakevar2 = 20; console. log (fakevar2, window. fakevar2); // 20 20 fakevar = 30; console. log (fakevar, window. fakevar); // 30 delete window. fakevar1; // truedelete this. fakevar2; // truedelete fakevar; // trueconsole. log (fakevar1, window. fakevar1); // error console. log (fakevar2, window. fakevar2); // error console. log (fakevar, window. fakevar); // Error
Javascript global variables are attributes of global objects, which are mandatory in ECMAScript. Local variables are used as attributes of an object related to function calls. ECMAScript3 is called a call object, and ECMAScript5 is called a declarative environment record ). Javascript allows the use of the this keyword to reference global objects, but it cannot reference objects stored in local variables. This special property that stores local variable objects is an internal implementation that is invisible to us.
The above basic javascript syntax-a comprehensive understanding of variables and identifiers is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for our customer base.