A, grammar,
1. Basic Grammar
-
Case sensitive
- Variables, function names, and operators are case sensitive. In other words, variables
test
And variablesTest
It’s two different variables.
- Variables, function names, and operators are case sensitive. In other words, variables
-
Identifier (variable) naming
- The value consists of letters, underscores (_), and dollar signs ($), and must start with a non-digit letter.
- The letters in the identifier can be extensions
ASCII
(Extended ASCII), can also beUnicode
Is, for example, A and æ is not recommended. - recommendedHump named, such as:
userInfo
. This form is consistent with the naming of ECMAScript built-in functions and objects.
Note: Keywords, reserved words, true, false, and NULL cannot be used as identifiers.
-
annotation
- Single-line comments:
// ...
- Multiline comment:
/ *... * /
Use hotkeys!
In most editors, a line of code can be commented on a single line using the Ctrl+/ hotkey, while the Ctrl+Shift+/ hotkey can be commented on multiple lines (select the code, then press the hotkey).
On macs, use Cmd instead of Ctrl and Option instead of Shift.
- Single-line comments:
-
statements
- In order toA semicolon
;
Space. In general, line breaks are also treated as delimiters, so semicolons are not used in line breaks.- Adding a semicolon helps:
- Avoid problems caused by ellipsis, such as incomplete input.
- It makes it easier for developers to compress code by removing empty lines.
- This can help improve performance in some cases, as the parser tries to fill in semicolons in the right places to correct syntax errors.
- Adding a semicolon helps:
- Multi-line statements can use code blocks
{}
Wrapped up.Block code does not need to be followed by a semicolon, but there will be no error, will be ignored automatically.- You can make your content clearer and reduce the likelihood of errors when you need to change your code.
- In order toA semicolon
An example of an error caused by not adding a semicolon:
/ / 1
[1.2].forEach(alert) // Display 1, then display 2
/ / 2
alert("There will be an error")
[1.2].forEach(alert)
// Only the contents of the first alert statement are displayed, then we receive an error!
// Because JavaScript does not use square brackets [...] Add an implicit semicolon before
// alert("There will be an error")[1, 2].forEach(alert)
/ / 3
alert("All fine now");
[1.2].forEach(alert)
There will be an error, then 1, then 2
Copy the code
2. Strict mode'use strict'
JavaScript has evolved over time without causing any compatibility problems. New features are added and old features remain unchanged.
This is good for compatibility with older code, but the downside is that any mistakes or imperfect decisions made by the JavaScript creator will also remain in the JavaScript language forever.
This continued until the advent of ECMAScript 5 (ES5) in 2009. The ES5 specification adds new language features and modifies some existing features. Most of the changes are disabled by default in order to ensure that the old functionality is still available. You need a special preprocessor directive — ‘use strict’ — to explicitly activate these features. Some non-standard writing of ECMAScript 3 is handled in this mode and errors are thrown for unsafe activities.
Note: ‘use strict’ must be at the top of the script or at the beginning of the function body to be effective:
/ / 1.
alert('some code');
// The following "use strict" is ignored and must be at the top.
'use strict';
// Strict mode is not activated
/ / 2.
'use strict';
alert('some code');
// Strict mode activation
Copy the code
We can specify a single function to execute in strict mode by placing this preprocessor at the beginning of the function body:
function doSomething() {
'use strict';
/ / the function body
}
Copy the code
All modern browsers support strict mode.
There is no way to cancel
use strict
There is no directive like “no use strict” to return the program to default mode. Once you’re in strict mode, there’s no going back.
Some modern features of the language, such as classes and modules, automatically enable Use Strict.
2.1 Browser console startsuse strict
When you run code using the developer console, note that it does not enable Use Strict by default.
Sometimes, when use Strict has some effect on your code, you get the wrong result.
So, how do I enable Use Strict in the console?
First, you can try typing multiple lines of code with the Shift+Enter key, and then place use strict at the top of the code like this:
'use strict';
//... Your code < press Enter to run >
+enter>Copy the code
It works in most browsers, like Firefox and Chrome.
If that still doesn’t work, for example if you’re using an older browser, there’s an ugly but reliable way to enable Use Strict. Put your code in a wrapper like this:
(function() {
'use strict';
/ /... Your code...}) ()Copy the code
Variable declaration
1.let
、var
和 const
-
var
-
Can be repeated declarations;
-
Scope: global scope, function scope;
Note: There is no block-level scope. Because in early JS, blocks had no lexical environment.
-
When a variable is declared using var, it is automatically added to the nearest context;
-
Omitting the var operator when defining a variable inside a function automatically adds it to the global context and makes it accessible outside the function (ReferenceError is not recommended in strict mode).
-
Variables that are not defined within a function are added to the global context. The browser’s global context object is the Window object, through which variables can be accessed. (For Node.js, its name is “global,” but other environments may use a different name. It has a common name, globalThis, which should be supported by all environments.
-
In browsers, global functions and variables declared using var become properties of global objects unless we use modules.
-
-
Variable promotion is performed (i.e., pre-declaration: no error is reported before declaration).
The VAR declaration is carried to the top of the function or global scope, before all the code in the scope. This phenomenon is called “ascending.” Promotion lets code in the same scope be used without regard to whether a variable is declared (output undefined instead of Reference Error).
Note: declarations are promoted, but assignments are not. The declaration is handled as soon as the function is executed (” promoted “), but assignment always takes effect where it appears.
-
-
let
-
Cannot be declared repeatedly under the same scope (block);
- Error reporting on declaration redundancy is not affected by mixing let and var.
-
Scope: global scope, block-level scope (defined by the nearest pair of enclosing braces {});
Block scopes are subsets of function scopes, so the same scope restrictions that apply to var also apply to LETS.
-
Will not promote (declare first, then use).
- The moment of execution before a LET declaration is known as a “temporal dead zone,” in which references to any variables declared later will raise a ReferenceError.
Strictly speaking, let is also promoted in JavaScript runtime, but because of “temporary dead zones” you can’t actually use let variables before declaration. Therefore, from the standpoint of writing JavaScript code, let is not promoted in the same way as VAR.
-
-
const
-
Constants can only be assigned at declaration time, and cannot be changed once assigned;
-
The outer layer of a const object cannot be changed, but the inner layer can;
-
To keep the inner layer unchanged, use Object.freeze(obj) to freeze the Object. This will not report an error when assigning a value to the property, but will silently fail.
-
-
Cannot repeat the declaration;
-
Scope: block-level scope;
-
It doesn’t go up.
-
In strict mode, you cannot define variables named eval and arguments, which would cause syntax errors.
1.1 var
// 1. Var can be repeated
var a = 1;
var a = 12; // This var is invalid because the variable is already declared and overwrites if it has a value.
console.log(a) / / 12
var a; // This var is invalid because the variable has already been declared. No value is overwritten.
console.log(a) / / 12
// 2. Scope
// Variables are initialized undeclared and added to the global context
function add(num1, num2) {
sum = num1 + num2; // Variables are initialized undeclared and are automatically added to the global context
return sum;
}
let result = add(10.20); / / 30
console.log(sum); / / 30
// Sum is added to the global context, persists after the function exits, and can be accessed outside the function
// 3. Properties of the browser global object Window
var name = 'Matt';
console.log(window.name); // 'Matt' is promoted to the global context. The browser's global context is the window object
// 4. Variable promotion
function sayHi() {
phrase = "Hello";
if (false) {
var phrase;
}
alert(phrase);
}
sayHi();
/ /... Technically, it is the same as the following case (' var phrase 'is moved up to the beginning of the function) :
function sayHi() {
var phrase;
phrase = "Hello";
if (false) {
}
alert(phrase);
}
sayHi();
// Note: declarations are promoted, but assignments are not
function sayHi() {
console.log(phrase);
var phrase = "Hello";
}
sayHi(); // undefined
/ / is equivalent to
function sayHi() {
var phrase;
console.log(phrase);
phrase = "Hello";
}
sayHi(); // undefined
Copy the code
1.2 let
// 1. Let cannot be repeated
let a = 1
let a = 2 / / an error
// 1.1 Error reporting for declaration redundancy is not affected by mixing let and var
let a = 1
var a = 2 / / an error
// 2. Block scope
// This is not an object literal, but a separate block
// The JavaScript interpreter will recognize it based on its contents
{
let a;
}
console.log(a); // ReferenceError: A is not defined
// 3. Let is not promoted
console.log(e) // ReferenceError: e is not defined.
let e = 1
Copy the code
1.3 const
// 1.1 Constants must be assigned when declared
const b; // SyntaxError: Missing initializer in const declaration.
// 1.2 Constants cannot be modified once assigned
const d = 20;
d = 30; // TypeError: Assignment to constant variable.
// 1.3 Const object freezes
// Const only fixes the value of the object, not the contents of the value.
// Only if we try to set 'obj=... When assigned as a whole, const throws an error.
const obj = {name: 'Joe'.age: 20}
// obj = {TypeError: Assignment to constant variable} // TypeError: Assignment to constant variable
// The outer layer of a const object cannot be changed, but the inner layer can
obj.name = 'bill' / / is not an error
console.log(obj) // {name: 'li ', age: 20}
// To keep the inner layer unchanged, use object.freeze (obj) to freeze the Object
Object.freeze(obj);
obj.name = 'Cathy' // No error, but no change
console.log(obj) // {name: 'li ', age: 20}
// 2. Do not repeat the declaration
const a = 1
const a = 2 / / an error
// 3. No promotion
console.log(g) // ReferenceError: 'g' cannot be accessed before initialization
const g = 20
Copy the code
2,let
与 var
The difference of
-
Var can be repeated, let can not be repeated.
-
The scope of the let declaration is block scope, and the scope of the var declaration is function scope.
-
Var is variable promoted, let is not promoted (temporary dead zone).
-
Declaring var to hang on the window object in the global scope does not.
-
Let cannot rely on the conditional declaration pattern. Because let is a block-level scope, the scope declared by let in a conditional block is limited to that block.
/* 1. Repeat declaration */
Var can be declared repeatedly
var a = 1;
var a = 2
console.log(a) / / 2
// 1.2 let cannot be repeated
let a = 1
let a = 2 / / an error
/* 2. Scope */
if(true) {
let b = 2; // block-level scope
// var b = 4; // let cannot be declared repeatedly in the same scope. Error reporting on declaration redundancy is not affected by mixing let and var.
var c = 3; // Function scope
console.log(b); / / 2
}
// console.log(b); // ReferenceError: b is not defined
console.log(c); / / 3
/* 3. */
// 3.1 var will be improved
console.log(d) // undefined
var d = 1
/ / equivalent to the
var d;
console.log(d);
d = 1;
// 3.2 let will not be promoted
console.log(e) // ReferenceError: e is not defined.
let e = 1
/* 4. The property of the window object */
var name = 'Matt';
console.log(window.name); // 'Matt' is promoted to the global context. The browser's global context is the window object
let age = 26;
console.log(window.age); // undefined
/* 5. Condition statement */
<script>
let name = 'Nicholas';
let age = 36;
</script>
<script>
// Assuming the script is not sure whether a variable of the same name has already been declared in the page, it can assume that it has not
if (typeof name === 'undefined') {
let name;
}
name = 'Matt'; // Name is limited to the scope of the if {} block, so this assignment is like a global assignment
try {
console.log(age);
}
catch(error) {
let age;
}
age = 26; // Age is limited to the scope of the catch {} block, so this assignment is like a global assignment
</script>
Copy the code
Statement style and best practices
-
Do not use
var
- This helps improve code quality because variables have clear scopes, declared locations, and immutable values.
-
const
Give priority to,let
second-
Because a const declaration implies that the value of a variable is of a single type and cannot be modified, the browser runtime compiler can replace all instances of it with the actual value without looking up the variable through a query table, leaving the variable unchanged;
-
Let static code analysis tools detect illegal assignment operations ahead of time. Allows developers to quickly detect unexpected behavior caused by unexpected assignments.
-
-
Let Manual address: developer.mozilla.org/zh-CN/docs/…
-
Const manual address: developer.mozilla.org/zh-CN/docs/…
4. Interview questions:var
,let
,const
The difference between
var
可Repeat statement;Declaration hangs inwindow
On the object;Function scope; willVariable ascension;let
Duplicate declarations are not allowed; Not throughwindow
Access;Block-level scope;Invariant promotion; Pre-declaration use will result in”Temporary dead zone“;const
Duplicate declarations are not allowed;Once declared, no changes are allowed (note the object, the inner layer can be changed); Not throughwindow
Access;Block-level scope;Invariant promotion;
Keywords and reserved words
Ecma-262 describes a set of reserved keywords that have special uses, such as indicating the beginning and end of a control statement, or performing a specific operation. By rule, reserved keywords cannot be used as identifiers or attribute names.
All the keywords specified in ecMA-262 version 6 are as follows:
break | do | in | typeof |
case | else | instanceof | var |
catch | export | new | void |
class | extends | return | while |
const | finally | super | with |
continue | for | switch | yield |
debugger | function | this | |
default | if | throw | |
delete | import | try |
The specification also describes a set of future reserved words that 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.
Here are all the words reserved for the future in ECMA-262 Version 6:
Always reserved:
The title | |
---|---|
enum |
Reserved in strict mode:
implements | package | public |
interface | protected | static |
let | private |
Reserved in module code:
The title | |
---|---|
await |
Do not use keywords and reserved words as identifiers and attribute names to ensure compatibility with past and future versions of ECMAScript.