0x01
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
0x02: Defining
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
//变量var Identifier = 123;//属性(new Object).Identifier = ‘test‘;//函数及参数function IdentifierName(Identifier1){};//跳转标记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 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.
0X02: 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
保留字 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 Infinity isFiniteisNaN JSON Math NaN Number Object parseFloat parseInt RangeErrorReferenceError RegExp String SyntaxError TypeError undefined URIError
JavaScript identifier names allow letters, numbers, dollar signs, and underscores (but the first character is not allowed to be a number)
//错误示范 6num //开头不能用数字 %sum //开头不能用除(_ $)外特殊符号,如(% + /等) sum+num //开头中间不能使用除(_ $)外特殊符号,如(% + /等)
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‘;
[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
类型 前缀 示例 数组(Array) a aItems布尔值(Boolean) b bIsComplete浮点数(Float) f fPrice函数(Function) fn fnHandler整数(Integer) i iItemCount对象(Object) o oDIv1正则表达式(RegExp) re reEmailCheck字符串(String) s sUserName变量(Variant) v
The above naming method, called the Hungarian nomenclature. This naming method is not recommended by current mainstream programming specifications
In general, the name of a variable uses a noun, and the function should be the verb + name form
var count = 10;var myName="xiaohuochai";var found = true;function getName(){ return 123; }
For variable naming, try to reflect the data type of the value in the variable name
For example, naming count, length, and size indicates that the data type is a number, whereas naming name, title, and message indicates that the data type is a string. Variables named with a single character, such as I, J, and K, are typically used in loops
For function and method naming, the first word should be a verb, and here are some common conventions for using verbs
can 函数返回一个布尔值has 函数返回一个布尔值is 函数返回一个布尔值get 函数返回一个非布尔值set 函数用来保存一个值
0X04: 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.
var message = ‘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<10; i++)console.log(i); 变量可以在声明时赋值,但不能有其他操作,如+=、-=等var a = 2;//是正确的var a += 2;//是错误的var a = 2++;//是错误的,++只能用于变量,不能用于常量
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, which 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>‘use strict‘;a = 5;console.log(a);</script>
0X05: 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 the dynamic type language
In JavaScript, you can modify the type of a value while modifying the value of a variable
var message = ‘hi‘;message = 100;//有效,但不推荐
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.
0X06: Variable Scope
A variable's scope (scope) is the area in the program's 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);//错误 如果省略var操作符,则会创建一个全局变量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);//undefined var scope = ‘local‘; console.log(scope);//‘local‘}//变量声明提升之后,相当于下面代码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 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.
Note ie8-Browser, if you delete the Window property, no matter how the property is created, an error will be
window.fakevar1 = 10;this.fakevar2 = 20;var fakevar3 = 30;fakevar4 = 40;console.log(delete fakevar1);//IE8-浏览器报错,其他浏览器返回trueconsole.log(delete fakevar2);//IE8-浏览器报错,其他浏览器返回trueconsole.log(delete fakevar3);//所有浏览器都返回falseconsole.log(delete fakevar4);//所有浏览器都返回true
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
Resources
"1" es5/syntax https://www.w3.org/html/ig/zh/wiki/ES5/lexical
"2" Ruan one peak JavaScript standard reference Tutorial--Grammar Overview http://javascript.ruanyifeng.com/grammar/basic.html
"3" W3school-javascript Advanced Tutorial--ecmascript variable http://www.w3school.com.cn/js/pro_js_variables.asp
"4" JavaScript Definitive Guide (6th edition) 3rd Chapter type, value, and variable
"5" JavaScript Advanced Programming (3rd Edition), chapter 3rd Basic Concepts, chapter 4th variables, scope, and memory issues
"6" JavaScript Language Essence (Revised edition), chapter 2nd syntax
"7" JavaScript DOM Programming Art (2nd Edition), chapter 2nd JavaScript syntax
Javascrip Variables and identifiers