Regarding JavaScript, the first more important concept is variables, and the working mechanism of variables is the basic feature of JavaScript. In fact, variables are a type of identifier. This article will introduce variables and identifiers in detail
definition
Identifier is a name used to name variables, functions, properties, and parameters, or to use it as a marker for jump positions in certain loop statements.
//Variable var Identifier = 123;//Properties(new Object).Identifier = 'test';//Function and parameters 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, a person's name and birthday are fixed, but his mood and age will change over time. People call things that change variables
When the program needs to save the value for future use, it is assigned to a variable. Variable is a placeholder for saving values. You can obtain a reference to the value through the variable name.
Naming rules
In the article "Lexicon Structure", we introduce that javascript is a case-sensitive language. Like any other programming language, javascript retains some identifiers for itself, and reserved words cannot be used as ordinary identifiers.
[Note] Reserved words include keywords, future reserved words, empty literals and boolean literals
ReservedWord :: Keyword FutureReservedWord NullLiteral BooleanLiteral
JavaScript identifier name is allowed to contain letters, numbers, dollar signs and underscores (but the first character is not allowed to be a number)
//Error demonstration 6num //The number %sum cannot be used at the beginning //The special symbols except (_$) cannot be used at the beginning, such as (% + / etc.) sum+num //The special symbols except (_$) cannot be used at the beginning, such as (% + / etc.)
JavaScript allows letters and numbers (including Chinese) in the entire set of Unicode characters 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 ease of writing, we usually do not use extended ASCII or Unicode characters
Usually camel format is the preferred format for identifier naming, the first letter is lowercase, and the first letter of each remaining word is uppercase.
var myMoodToday = 'happy';
For different data types, JavaScript has conventional identifier naming rules
Type prefix example array (Array) a aItems Boolean (Boolean) b bIsComplete floating point number (Float) fPrice function (Function) fn fnHandler integer (Integer) iiItemCount object (Object) o oDIv1 regular expression (RegExp) re reEmailCheck string (String) s sUserName variable()Variant v vAnything
Variable declaration
statement
In javascript, you should declare (declare) before using a variable. The variable is declared using the keyword var (the abbreviation of variable).
var i;var sum;
You can also declare multiple variables through a var keyword
var i ,sum;
Assignment
The operation of storing values into variables is called assignment. After a variable is assigned, we say that the variable contains this value
The process of assigning a variable for the first time is called initialization
We can write the initial assignment of variables together with the variable declaration
var message = 'hello';var i=0,j=0,k=0;
If the variable is not specified in the var declaration statement, even though the variable is declared, its initial value is undefined before saving a value to it
Var statements can also be used in for loops and for-in loops, which can more concisely declare loop variables used in loop syntax
for(var i=0; i<10; i++)console.log(i);
Variables can be assigned values when declared, but there cannot be other operations, such as +=, -=, etc.
var a = 2;//is correct var a += 2;//is wrong var a = 2++;//is wrong, ++ can only be used for variables, not constants
Repeat statement
It is legal and harmless to repeatedly declare variables using var statements. If the declaration is repeated with assignment operations, it is equivalent to reassigning the value.
Missing statement
If you try to read the value of a variable that is not declared, javascript will report an error
JavaScript allows omitted declarations, that is, directly assigning values to variables without prior declarations, and the assignment operation will automatically declare the variable.
However, in ECMAScript5 strict mode, assigning a value to an undeclared variable will result in an error
<script>'use strict';a = 5;console.log(a);</script>
Variable characteristics
JavaScript variables are weak types (also called loose types), and the so-called loose types are used to save any type of data.
Programming language classification: dynamic typed language and static typed language. Dynamic typed language refers to a language that only does data type checking during operation. That is to say, when programming in a dynamic typed language, you do not need to specify a data type for any variable. The language will record the data type internally when the first time it assigns a value to a variable. JavaScript is the representative of dynamically typed languages.
In javascript, you can modify the type of the value while modifying the value.
var message = 'hi';message = 100;//Valid, but not recommended
There are two points to summarize the characteristics of loose types of variables: one is that you do not need to specify data types for variables when declaring; the other is that you can modify the data types when assigning values.
Variable scope
The scope of a variable, also known as the execution context, is the area that defines this variable in the program source code.
Scopes are divided into global scope and function scope (also called local scope)
The global scope is the most 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 window objects. Global variables have global scopes and are defined anywhere in javascript code. Global scope will not be destroyed until the application exits, for example, closes a web page or browser.
Variables declared within a function are only defined in the function body. They are local variables and their scope is local. Function parameters are also local variables, and they are only defined 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 it are also destroyed.
function test(){ var message = 'hi';}test();alert(message);//ErrorIf the var operator is omitted, 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 scope are difficult to maintain, and if the var operator is intentionally ignored, it will also cause unnecessary confusion because the corresponding variable will not be defined immediately. Assigning values to undeclared variables in strict mode will cause a ReferenceError error to be thrown
In the function body, the priority of local variables is higher than that of global variables with the same name. If a local variable declared in the function or the variable and global variables in the function parameter are duplicated, then the global variable is covered by the local variable.
var scope = 'global';function checkscope(){ var scope = 'local'; return scope;};checkscope();//'local'Statement promotion (hoisting)
Block-level scope
Block-level scope means that each piece of code in curly braces has its own scope, while JavaScript does not have a block-level scope. JavaScript only has function scope: variables are defined in the function body that declares them and any function body nested in this function body.
This means that variables are even available before they are declared. This feature of javascript is informally called hoisting. All variables declared in javascript functions (no assignments involved) are advanced to the top of the function body.
[Note] In fact, in addition to variable promotion, functions are also promoted, and there will be detailed introductions to the function section
var scope = 'global';function f(){ console.log(scope);//undefined var scope = 'local'; console.log(scope);//'local'} //After the variable declaration is promoted, it is equivalent to the following code var scope = 'global';function f(){ var scope; console.log(scope);//undefined scope = 'local'; console.log(scope);//'local'}There is no block-level scope in JavaScript, so some programmers deliberately put variable declarations on the top of the function body. This source code clearly reflects the real variable scope.
Attribute variables
When declaring a javascript global variable, it actually defines a property of the global object window
When a variable is declared using var, the created variable is not configurable, which means that 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 you do not use strict mode and assign a value to an undeclared variable, javascript will automatically create a global variable. The variables created in this way are normal configurable properties of the global object and can delete them
window.fakevar1 = 10;console.log(fakevar1,window.fakevar1);//10 10 this.fakevar2 = 20;console.log(fakevar2,window.fakevar2); //20 20fakevar = 30;console.log(fakevar,window.fakevar); //30 30delete window.fakevar1;//truedelete this.fakevar2;//truedelete fakevar;//trueconsole.log(fakevar1,window.fakevar1);//report error console.log(fakevar2,window.fakevar2); // Report an error console.log(fakevar,window.fakevar); // Report an error
JavaScript global variables are properties of global objects, which are mandatory in ECMAScript. Local variables are treated 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 this keyword to refer to global objects, 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
The above basic grammar of javascript - a comprehensive understanding of variables and identifiers is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.