Study notes 2—JavaScript language foundation

1 The difference and connection between ECMAScript and JavaScript

1. ECMAScript is the specification of JavaScript. JavaScript is an implementation of ECMAScript. In everyday situations, these two words are interchangeable.
Netscape, the creator of JavaScript, submitted JavaScript to ECMA, the International Organization for Standardization, hoping that this language could become an international standard. Later, ECMA released the first version of the standard document (ECMA-262), which stipulated the standard for browser scripting language, and Call this language ECMAScript. The standard was formulated for the JavaScript language from the very beginning. There are two reasons why it is not called JavaScript: one is a trademark. Java is a trademark of Sun. According to the license agreement, only Netscape can legally use the name JavaScript, and JavaScript itself has also been registered as a trademark by Netscape; the second is to reflect that the creator of this language is ECMA, not Netscape, which helps to ensure the openness and neutrality of this language.

2. But in fact, JavaScript has much more meaning than ECMA-262. A complete JavaScript implementation should consist of the following three parts:

  1. ECMAScript: the core

  2. DOM: Document Object Model

  3. BOM: Browser Object Model

2 Grammar

(1) Identifier: the name of a variable, function, attribute or function parameter. The first character must be a letter, underscore _, or dollar sign $. The remaining characters can be letters, underscores, dollar signs, or numbers.
By convention, ECMAScript identifiers use camel case, that is, the first letter of the first word is lowercase, and the first letter of each subsequent word is uppercase.
(2) Comments: ECMAScript uses C language style comments, including single-line comments and block comments. Single-line comments start with two slash characters, such as:

//单行注释

Block comments begin with a slash and an asterisk (/ ), and end with their reverse combination ( /), such as:

/*
这是多行注释
*/

(3) Keywords and reserved words
ECMA-262 describes a set of reserved keywords, these keywords have special purposes, such as indicating the beginning and end of a control statement, or performing specific operations. According to regulations, reserved keywords cannot be used as identifiers or attribute names.
The specification also describes a set of future reserved words, which cannot be used as identifiers or attribute names. Although reserved words have no specific purpose in the language, they are reserved for future use as keywords.
(4) Statements in
ECMAScript end with a semicolon, such as:

let sum = a+b
let diff = a-b;

Even if the semicolon at the end of the statement is not necessary, it should be added. Adding a semicolon is convenient for developers to compress code by deleting blank lines. Adding a semicolon can also help improve performance in some cases, because the parser tries to add a semicolon at the right place to correct syntax errors.

3 variables

ECMAScript variables are loose, which means that variables can be used to store any type of data. There are 3 keywords to declare variables: var, const, and let. Among them, var can be used in all versions of ECMAScript, while const and let can only be used in ECMAScript6 and later versions.

3.1 var

var message; //变量定义

Without initialization, the variable will hold a special value undefined.

var message = "hi"; //变量定义同时设置值

(1) Var declaration scope
The variable defined by the var operator becomes the local variable of the function containing it. For example, using var to define a variable inside a function means that the variable will define a variable inside the function, which means that the variable will be destroyed when the function is launched.

        function test(){
    
    
            var message = "hi"; //局部变量
        }
        test();
        console.log(message); //出错!

Here the message variable is defined using var inside the function. The function is called test(), calling it will create this variable and assign a value to it. The variable is destroyed immediately after the call, so an error is reported. However, you can create a global variable by omitting the var operator when defining a variable in a function.

        function test(){
    
    
            message = "hi"; //全局变量
        }
        test();
        console.log(message); //“hi”

After removing the previous var operator, the message becomes a global variable. As long as the function test() is called once, this variable will be defined and can be accessed outside the function.
If you need to define multiple variables, you can separate each variable with a comma in a statement:

var message = "hi",found = false,age = 29;

Because ECMAScript is loosely typed, variables initialized with different data types can be declared with one statement.
(2) Var declaration promotion
When using var, the following code will not report an error, because the variable declared with this keyword will be automatically promoted to the top of the function scope:

        function foo() {
    
    
            console.log(age);
            var age = 26;
        }
        foo();

The reason why no error is reported is because ECMAScript runs it as equivalent to the following code:

        function foo() {
    
    
            var age;
            console.log(age);
            age = 26;
        }
        foo(); //undefined

This is hoist, which is to pull all variable declarations to the top of the function scope. In addition, there is no problem with repeatedly using var to declare the same variable:

        function foo() {
    
    
            var age = 16;
            var age = 26;
            var age = 36;
            console.log(age);
        }
        foo(); //36

3.2 let

(1) Let and var have similar functions, but there are very important differences. The most obvious is that the scope of let declaration is block scope, while the scope of var declaration is function scope .

        if (true){
    
    
            var name = 'lq';
            console.log(name); //lq
        }
        console.log(name); //lq

        if(true){
    
    
            let age = 26;
            console.log(age); //26
        }
        console.log(age); //ReferenceError:age没有定义

The age variable cannot be referenced outside the if block because its scope is limited to the inside of the block. Block scope is a subset of function scope, so the scope restrictions that apply to var also apply to let.
(2) Let also does not allow redundant declarations in the same block scope :

var name;
var name;

let age;
let age; //SyntaxError; 标识符age已经声明过了

No error will be reported if the same identifier is nested:

let age = 30;
console.log(age); //30
if (true) {
    
    
	let age = 26;
	console.log(age); //26
}

The redundant reporting of declarations will not be affected by mixing let and var. These two keywords do not declare different types of variables, they just indicate how the variable exists in the relevant scope:

var name;
let name; //SyntaxError

let age;
var age; //SyntaxError

(3)
Another important difference between let and var is the temporary dead zone that the variable declared by let will not be promoted in scope .

//name会被提升
console.log(name); //undefined
var name = 'Matt'//age不会被提升
console.log(age); //ReferenceError:age没有定义
let age = 26;

(4) Global declaration
Unlike the var keyword, variables declared in the global scope using let will not become properties of the window object (variables declared by var will).

        var name = 'Matt';
        console.log(window.name); //'Matt'

        let age = 26;
        console.log(window.age); //undefined

Let declaration
in the for loop Before let appears, the iteration variables defined by the for loop will penetrate outside the loop body:

        for (var i = 0; i < 5; ++i) {
    
    
            //循环逻辑
        }
        console.log(i); //5

This problem disappeared after changing to let, because the scope of the iteration variable is limited to the inside of the for loop:

        for (let i = 0;i<5;++i){
    
    
            //循环逻辑
        }
        console.log(i); //ReferenceError: i没有定义

3.3 const

The behavior of const is basically the same as that of let. The only important difference is that when you use it to declare a variable, you must initialize the variable at the same time, and trying to modify the const-declared variable will cause a runtime error.

const age = 26;
age = 36; //TypeError:给常量赋值

//const也不允许重复声明
const name = 'Matt';
const name = 'Nicholas'; //SyntaxError

//const声明的作用域也是块
const name = 'Matt';
if (true){
    
    
	const name = 'Nicholas';
}
console.log(name); //Matt

If the const variable refers to an object, then modifying the internal properties of this object does not violate the const restriction. But it cannot be reassigned to other reference values.

const person = {
    
    };
person.name = 'Matt';

3.4 Statement style and best practices

(1) Don't use var.
With let and const, most developers will find that they no longer need var. Restricting yourself to only use let and const helps to improve code quality, because variables have a clear scope, declaration position, and constant value.
(2) Const first, let second.
Using const declarations can force the browser to keep variables unchanged during runtime, and it can also allow static code analysis tools to detect illegal assignment operations in advance. Therefore, many developers think that const should be used to declare variables first, and let only when they know in advance that there will be changes in the future. This allows developers to more confidently infer that the value of certain variables will never change, and at the same time quickly discover unexpected behaviors caused by accidental assignments.

to sum up:

where let const
Scope Function scope Block scope Block scope
Whether to be hoist Yes no no
Can you repeat the statement can Can't Can't

Guess you like

Origin blog.csdn.net/qq_43599049/article/details/112757665