3.1 introduction

This chapter begins by learning the basics of the ES6-based language, covering syntax, operators, data types, and built-in functionality.

3.2 MIND

3.3 grammar

ECMAScript’s syntax borrows heavily from C and other C-like languages such as Java and Perl.

  • Case sensitive: Everything in ECMAScript is case sensitive, whether it’s variables, function names, or operators
  • 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
    • Camel case by convention (best practice)
    • Keywords, reserved words, true, false, and NULL cannot be used as identifiers
  • annotation: Single line and block comments (C style)
    // Single-line comment
    
    /* Multi-line comments */
    Copy the code
  • Strict mode: ES5 adds Strict mode, which is a different model for JavaScript parsing and execution. This can be done by adding a line “Use strict” at the top of the script outside the function, or inside the function itself.
  • Statements: Control statements that end with a semicolon use code blocks

3.4 Keywords and Reserved Words

! Cannot be used as an identifier

ES6 keyword

break       do          in           typeof
case        else        instanceof   var
catch       export      new          void
const       finally     super        with
continue    for         switch       yield
debugger    function    this
default     if          throw
delete      import      try
Copy the code

The ES8 keyword adds await

ES6 reserved words

  • Always keep
    enum
    Copy the code
  • Reserved in strict mode
    implements  package     public
    interface   protected   static
    let         private
    Copy the code
  • Reserved in the module code
    await
    Copy the code

3.5 variable

3.5.1 Var Keyword

Var can be used to define any type of variable, undefined if not initialized.

Main Contents:

  • Var declares scope
    • Variables defined within a function are local variables of the function and are destroyed when the function exits.
    • Omit the var operator to define global variables (not recommended)
  • Var declaration enhancement
    • Variables can be used normally before being declared inside a function

3.5.2 let statement

Differences with VAR:

  • The scope of the let declaration is block scope, and the scope of the var declaration is function scope
  • Let is not repeatable and var is repeatable
  • Variables declared by lets are not promoted in scope, whereas var can be promoted
  • In the global scope, let declared variables do not become properties of the Window object, whereas var does.

Error: Use let and var to declare the same variable

Main Contents:

  • Temporary dead zone

    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.

  • Global declarations

    Variables declared by lets in the global scope do not become properties of the Window object.

  • Condition statements

    You cannot use let for conditional declarations.

  • Let declaration in the for loop

    Before let, the iterated variables defined by the for loop would leak out of the loop body. After let, the scope of the iterated variables is limited to the inside of the for loop block.

3.5.3 const statement

  • A const must initialize a variable when it is declared
  • Variables declared by const cannot be modified
  • Cannot duplicate declaration
  • Block scope
  • If a const variable refers to an object, the object properties can be modified
  • Cannot declare an iterated variable (incremented) using const

3.5.4 Declare style and best practices

  • Do not use the var
  • Const takes precedence over let

3.6 Data Types

ES6 contains six basic data types (primitive types) : Undefined, Null, Boolean, Number, String, and Symbol(Symbol was added to ES6). A complex data type is called Object.

ES11 new basic data type BigInt (integer with arbitrary precision)

3.6.1 Typeof operator

Determines the data type of any variable

Seven data types:

  • “Undefined undefined”
  • “Boolean” Boolean value
  • “Number”
  • “String” string
  • “Symbol” means the value is a symbol
  • “Object” objects (not functions) or NULL
  • “Function” function

3.6.2 Undefined type

  • Undefined has only one value, which is the special value Undefined
  • Whether declared or undeclared, Typeof returns the string “undefined”

    It is recommended that variables be initialized at the same time as they are declared, so that when Typeof returns “undefined” it is known that the given variable is undeclared, rather than declared but uninitialized.

Never explicitly set undefined to a variable. The literal undefined is mainly used for comparison and did not exist prior to ES3. The purpose of adding this special value is to formalize the difference between a null object pointer and an uninitialized variable.

3.6.3 Null type

  • The Null type also has only one value, the special value Null
  • Undefined values are derived from null values, so ECMA-262 defines them as ostensibly equal (literals equal)
  • It is recommended to use NULL to initialize an empty object instead of undefined

3.6.4 radar echoes captured a Boolean type

  • The Boolean type is one of the most frequently used types in ECMAScript and has two literals: true and false
  • All other ECMAScript type values have the equivalent form of the corresponding Boolean value, which can be obtained through the Boolean() transformation function
  • Flow control statements such as if automatically convert values of other types to Booleans (automatic type conversion)

3.6.5 Number type

  • The Number type uses IEEE 754 format to represent integer and floating point values (also called double values in some languages)
  • Have different base formats

    Common base formats such as binary, octal (starting with 0), decimal, hexadecimal (starting with 0x)

3.6.5.1 floating point value

  • Contains a decimal point and must be followed by at least one number
  • Very large or very small floating-point values can be expressed in scientific notation
  • Floating-point values are accurate to up to 17 decimal places, but are far less accurate in arithmetic than integers

    For example, instead of 0.3, 0.1 plus 0.2 yields 0.300 000 000 000 000 000 04 (due to the use of IEEE754 values)

3.6.5.2 Range of values

  • Number.min_value: The smallest Number that ECMAScript can represent (5E-324 in Number browsers)
  • MAX_VALUE: The maximum value that ECMAScript can express (1.797 693 134 862 315 7e+308 in most browsers)
  • Values outside the range that JavaScript can represent are automatically converted to Infinity

3.6.5.3 NaN

  • The value is NaN, which means “Not a Number.”
  • Any operation involving NaN always returns NaN (e.g. NaN/10)
  • NaN is not equal to any value including NaN (NaN! = NaN)
  • The isNaN() function lets you determine if a parameter is “not a number”

3.6.5.4 Numerical Conversion

There are three functions to convert non-numeric values to numeric values: Number(), parseInt(), and parseFloat()

Number() function conversion rules:

  • Boolean values that convert true to 1 and false to 0
  • Value, return directly
  • Null returns 0
  • Undefined, return NaN
  • string
    • If the string contains numeric characters (including those preceded by a plus or minus sign), it is converted to a decimal value
    • If the string contains a valid floating-point value format, it is converted to the corresponding floating-point value
    • If the string contains a valid hexadecimal format such as “0xf”, it is converted to the decimal integer corresponding to the hexadecimal value
    • If it is an empty string (containing no characters), 0 is returned
    • If the string contains characters other than the above, NaN is returned
  • Object that calls the valueOf() method and converts the returned value according to the rules above. If the conversion results in a NaN, the toString() method is called and converted according to the rules for converting strings

ParseInt () function conversion rules:

  • The first space in the string is ignored, and the first non-space character is converted
  • The first character is not a numeric character, plus or minus, and immediately returns NaN (empty strings also return NaN)
  • Ignore the decimal point and subsequent digits
  • The base number is specified by the second argument

ParseFloat () function conversion rules:

  • The first occurrence of the decimal point is valid, the second occurrence of the decimal point is invalid
  • You cannot specify an exponent as an argument, that is, only convert to decimal

3.6.6 BigInt Type (ES11)

  • Represents an integer of arbitrary precision, followed by n
  • Arithmetic operations cannot be performed using a mixture of Number and BigInt operands (either type needs to be explicitly converted)
  • For compatibility reasons, the unary plus (+) operator is not allowed on BigInt

3.6.7 type String

The String data type represents a sequence of zero or more 16-bit Unicode characters. Strings can be marked with double quotation marks (“), single quotation marks (‘), or backquotation marks (‘).

3.6.7.1 Character literals

literal meaning
\n A newline
\t TAB
\b backspace
\r enter
\f Change the page
\ \ The backslash (\)
\ ‘ Single quotation marks (‘), used when a string is marked with single quotation marks, such as ‘He said, \’hey.\”
\” Double quotation marks (“), used when a string is marked with double quotation marks, for example, “He said, \”hey.\””
\ ` Backquotes (‘), used when a string is marked with backquotes, e.g. ‘He said, \’ hey.\ ‘
\xnn A hexadecimal character denoted by nn (where n is the hexadecimal number 0 to F), for example \x41 equals “A”
\unnnn Unicode characters in hexadecimal encoding NNNN (where n is the hexadecimal digits 0 to F), such as \ u03A3 equals the Greek character “σ”

3.6.7.2 Characteristics of Strings

Immutable, cannot be changed once the value is created

3.6.7.3 Converting to a String

  • toString()
    • Can be used for numeric, Boolean, object, and string values
    • Cannot be used for null and undefined values
    • Can be used for numeric parameters (base number)
  • String()
    • If the value has a toString() method, that method is called (with no arguments) and the result is returned
    • If the value is null, return “null”
    • If the value is undefined, return undefined

To determine whether a value is null or undefined, use the String() function

3.6.7.4 Template literals

let templateLiteral = `first line
second line`
Copy the code

3.6.7.5 String Interpolation

let interpolatedTemplateLiteral = `Hello ${ name }! `;
Copy the code

3.6.7.6 Template literal tag function

Template literals also support defining tag functions that allow you to customize the interpolation behavior.

let a = 6;
let b = 9;
function simpleTag(strings, ... expressions) {
    console.log(strings);
    for(const expression of expressions) {
        console.log(expression);
    }
    return 'foobar';
}
let taggedResult = simpleTag`${ a } + ${ b } = ${ a + b }`;
// ["", "+ "," = ", "]
/ / 6
/ / 9
/ / 15
console.log(taggedResult);  // "foobar"
Copy the code

3.6.7.7 Raw String

Template literals can also be used to retrieve the original template literal content (such as newlines or Unicode characters) rather than the converted character representation. To do this, you can use the default string. raw tag function:

/ / Unicode example
// \u00A9 is a copyright symbol
console.log(`\u00A9`);           / / ©
console.log(String.raw`\u00A9`); // \u00A9
Copy the code

3.6.8 Symbol type

Symbol is a new data type in ECMAScript 6. Symbols are primitive values, and symbol instances are unique and immutable. The purpose of the symbol is to ensure that object attributes are uniquely identified without the risk of attribute collisions.

3.6.8.1 Basic Usage

  • Class using the Symbol() function

    let sym = Symbol(a);console.log(typeof sym); // symbol
    Copy the code
  • Pass the parameter as a description of the symbol

    let genericSymbol = Symbol(a);let otherGenericSymbol = Symbol(a);let fooSymbol = Symbol('foo');
    let otherFooSymbol = Symbol('foo');
    
    console.log(genericSymbol == otherGenericSymbol);  // false
    console.log(fooSymbol == otherFooSymbol);          // false
    Copy the code

    String arguments have nothing to do with symbol definitions or identifiers

  • No literal syntax

    Creating an instance of Symbol() and using it as a new attribute of the object ensures that it does not overwrite existing object attributes

  • The Symbol() function cannot be used as a constructor with the new keyword

3.6.8.2 Using the Global symbol Registry

Create global Symbol: symbol.for ()

let fooGlobalSymbol = Symbol.for('foo');               // Create a new symbol
let otherFooGlobalSymbol = Symbol.for('foo');          // Reuse existing symbols
console.log(fooGlobalSymbol === otherFooGlobalSymbol); // true
Copy the code

Even if Symbol descriptions (parameters) are the same, symbol.for () and Symbol() define different symbols.

let localSymbol = Symbol('foo');
let globalSymbol = Symbol.for('foo');
console.log(localSymbol === globalSymbol); // false
Copy the code

Query global registry Symbol description: symbol.keyfor ()

Symbol.keyfor () receives the global Symbol and outputs the Symbol description. If the input is a non-global symbol, the output is undefined

3.6.8.3 Using symbols as attributes

Method:

  • Object literals as properties
  • Attribute defined by object.defineProperty ()/object.defineProperties ()
let s1 = Symbol('foo'),
    s2 = Symbol('bar'),
    s3 = Symbol('baz'),
    s4 = Symbol('qux');
    
let o = { 
  [s1]: 'foo val'
};
O [s1] = 'foo val';
console.log(o); 
// {Symbol(foo): foo val}

Object.defineProperty(o, s2, {value: 'bar val'});
console.log(o);
// {Symbol(foo): foo val, Symbol(bar): bar val}

Object.defineProperties(o, {
  [s3]: {value: 'baz val'},
  [s4]: {value: 'qux val'}});console.log(o);
// {Symbol(foo): foo val, Symbol(bar): bar val, Symbol(baz): baz val, Symbol(qux): qux val}
Copy the code

Related methods:

  • Object. GetOwnPropertyNames () : returns an Object instance of conventional attribute array
  • Object. GetOwnPropertySymbols () : returns the Object instance symbol attribute array
  • Object. GetOwnPropertyDescriptors () : returns include both conventional and symbolic attributes descriptor Object
  • Reflect.ownkeys () : Returns two types of keys
let s1 = Symbol('foo'),
    s2 = Symbol('bar');
    
let o = {
  [s1]: 'foo val',
  [s2]: 'bar val'.baz: 'baz val'.qux: 'qux val'
};

console.log(Object.getOwnPropertyNames(o));
// ["baz", "qux"]

console.log(Object.getOwnPropertySymbols(o));
// [Symbol(foo), Symbol(bar)]

console.log(Object.getOwnPropertyDescriptors(o));
// {baz: {... }, qux: {... }, Symbol(foo): {... }, Symbol(bar): {... }}

console.log(Reflect.ownKeys(o));
// ["baz", "qux", Symbol(foo), Symbol(bar)]
Copy the code

3.6.8.4 Common built-in symbols

  • The built-in symbols are in the form of string attributes of the Symbol factory function
  • Built-in symbols can be used to change the native structure
  • The built-in Symbol is a plain string property of the global function Symbol that points to an instance of a Symbol
  • All built-in symbolic properties are not writable, enumerable, or configurable

When referring to the ECMAScript specification, it is common to refer to the names of symbols in the specification, prefixed with @@. For example, @@iterator is symbol. iterator.

3.6.8.5 Symbol attribute

  • Symbol.asyncIterator specifies the default asynchronous iterator for an object. If an object has this property set, it is an asynchronous iterable and can be used for await… Of circulation.

  • Symbol. The prototype. The description description is a read-only attribute, it returns an optional description of the objects of Symbol strings.

  • Symbol. HasInstance is used to determine whether an object is an instance of a constructor.

  • Symbol. IsConcatSpreadable used to configure a particular object as an Array. The prototype. The concat () method whether the parameters of the Array elements.

  • Symbol.iterator defines the default iterator for each object. This iterator can be used by for… Of recycling.

  • Symbol.match specifies that regular expressions are matched instead of strings. The string.prototype.match () method calls this function.

  • Symbol.matchall returns an iterator that generates regular expression matches based on the string. This function can be a String. The prototype. MatchAll () method call.

  • Symbol.replace specifies the method to be called when a string replaces the matched string. The string.prototype.replace () method calls this method.

  • Symbol.search specifies a search method that takes a user-typed regular expression and returns the subscript that the regular expression matches in the String. This method is called by string.prototype.search ().

  • Symbol.species is a function-valued attribute that is used by constructors to create derived objects.

  • Symbol.split points to the method of splitting a string at the index of a regular expression. This method is called with string.prototype.split ().

  • Symbol.toPrimitive A built-in Symbol value that exists as a function value property of an object and is called when an object is converted to its original value.

  • Symbol.toStringTag A built-in Symbol that is usually used as the attribute key of an object. The corresponding attribute value should be a string representing the object’s custom type label. Usually only built-in Object. The prototype. The toString () method to read the label and put it in his own return values.

  • Symbol.unscopables refers to the name of the property used to specify the value of the object itself and the inherited property excluded from the with environment binding of the associated object.

The 3.6.9 Object type

An Object instance has the following properties and methods:

  • Constructor: The function used to create the current object. In the previous example, the value of this property was the Object() function.
  • HasOwnProperty (propertyName) : Used to determine whether a given property exists on the current object instance (not the prototype). The property name to be checked must be a string (such as O.hasownProperty (“name”)) or a symbol.
  • IsPrototypeOf (object) : Used to determine whether the current object is the prototype of another object.
  • PropertyIsEnumerable (propertyName) : Used to determine if a given property can be enumerable in a for-in statement (discussed later in this chapter). As with hasOwnProperty(), the property name must be a string.
  • ToLocaleString () : Returns a string representation of an object that reflects its localized execution environment.
  • ToString () : Returns a string representation of an object.
  • ValueOf () : Returns the string, numeric, or Boolean representation of an object. Usually the same as the return value of toString().

3.7 the operator

Ecma-262 describes a set of operators that can be used to manipulate data values, including mathematical operators (such as addition and subtraction), bitwise operators, relational operators, and equality operators. Operators in ECMAScript are unique because they can be used for a variety of values, including strings, numeric values, Bools, and even objects. When applied to objects, operators typically call valueOf() and/or toString() methods to get computable values.

3.7.1 Unary operators

Definition: Operators that operate on only one value are called unary operators. The unary operator is the simplest operator in ECMAScript.

  1. Increment/decrement operators: ++ and —

    • It can operate on any value
    • Preposition: increase or decrease before evaluating; Postposition: evaluate before adding or subtracting

    Rules:

    • For a string, if it is a valid numeric form, convert it to a numeric value and apply the change. The variable type changes from a string to a number.
    • For strings, if it is not a valid numeric form, set the value of the variable to NaN. The variable type changes from a string to a number.
    • For Boolean values, if false, convert to 0 and apply the change. The variable type changes from a Boolean to a numeric value.
    • For booleans, if true, convert to 1 and apply the change. The variable type changes from a Boolean to a numeric value.
    • For floating-point values, add or subtract 1.
    • If it is an object, its valueOf() method is called to get a value that can be manipulated. Apply the above rules to the resulting values. In the case of NaN, toString() is called and the other rules are applied again. The variable type changes from object to value.
  2. Unary addition and subtraction Unary addition is preceded by a plus sign (+), which has no effect on the value of the variable. Unary subtraction is indicated by a minus sign (-) placed at the head of a variable and used primarily to turn a value negative.

    Rules:

    • Using unary plus is equivalent to using Number(). Applying unary addition to a non-numeric value performs the same type conversion as using the Number() conversion function (Boolean values false and true are converted to 0 and 1, strings are parsed according to special rules, Objects call their valueOf() and/or toString() methods to get a value that can be converted.)
    • Using unary subtraction to a value turns it into a corresponding negative value. When applied to non-numeric values, unary subtraction follows the same rules as unary addition, converting them first and then taking negative values.

3.7.2 bit operators

Function: Operates on bits (bits) representing data in memory

All values in ECMAScript are stored in IEEE 754 64-bit format, but bitwise operations do not apply directly to 64-bit representations. Instead, values are converted to 32-bit integers, then bitwise operations are performed, and then the result is converted to 64-bit

Signed integer: The first 31 bits represent an integer value, and the 32nd bit (sign bit) represents the sign of the value (0 positive, 1 negative).

The binary of negative values: Negative values are stored in a binary code called the binary complement (or complement) and are computed as follows.

  1. Determine the binary representation of absolute value (e.g., for -18, determine the binary representation of 18 first)
  2. Find the complement (or inverse) of the numeric value, in other words, every 0 becomes a 1, and every 1 becomes a 0;
  3. Add 1 to the result.

Take negative +1: take positive -> take negative -> +1

Negative binary string: Absolute value preceded by a negative sign

let num = -18;
console.log(num.toString(2)); / / "- 10010"
Copy the code

3.7.3 Operations related to bit operators

3.7.3.1 Bitwise Not ~

Binary numeric bits and operation rules: take the inverse value is expressed as: take the inverse minus one

Case: ~25 === -26

NOT 25 = 0000 0000 0000 0000 0000 0000 0001 1001
------------------------------------------------
   -26 = 1111 1111 1111 1111 1111 1111 1110 0110
Copy the code

3.7.3.2 Bitwise and &

Binary each numeric bit and operation rule: 11 is 1, 0 is 0

Case :(25&3) === 1

 25 = 0000 0000 0000 0000 0000 0000 0001 1001
  3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
AND = 0000 0000 0000 0000 0000 0000 0000 0001
Copy the code

3.7.3.3 bitwise or |

Binary each numeric bit or operation rule: 1 is 1, 00 is 0

Case: (25 | 3) = = = 27

 25 = 0000 0000 0000 0000 0000 0000 0001 1001
  3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
 OR = 0000 0000 0000 0000 0000 0000 0001 1011
Copy the code

3.7.3.4 Bitwise XOR ^

Binary each numeric bit xOR operation rule: different 1, the same 0

Case :(25 ^ 3) === 26

 25 = 0000 0000 0000 0000 0000 0000 0001 1001
  3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1010
Copy the code

3.7.3.5 left < <

The left-shift operator, represented by two less-than signs (<<), moves all the bits of a value to the left by the specified number of bits.

A left shift preserves the sign of the value it manipulates. For example, if you move negative 2 5 places to the left you get negative 64 instead of positive 64.

3.7.3.6 Moved Right with Symbols >>

A signed right shift, indicated by two greater than signs (>>), moves all 32 bits of a value to the right while preserving the sign (positive or negative).

A signed shift to the right is actually the inverse of a shift to the left. For example, if you move 64 five places to the right, you get 2

3.7.3.7 Unsigned Right Move >>>

A sign shift to the right, represented by three greater than signs (>>>), shifts all 32 bits of the value to the right.

Negative service numbers moving right can result in very large results

case

let oldValue = -64; / / equal to binary 11111111111111111111111111000000
let newValue = oldValue >>> 5; // Is equal to the decimal 134217726
Copy the code

Unsigned 5 bits to the right of -64, the result is 134, 217, 726. That’s because the binary representation of -64 is 11111111111111111111111 1111111000000, and the unsigned right shift takes it as a positive value, which is 4 294, 967, 232. The value moves to the right after five, the result is 00000111111111111111111111111110, 134, 217, 726.

3.7.4 Boolean operators

3.7.4.1 Logical No!

Rules:

  • Return false if the operand is an object.
  • Returns true if the operand is an empty string.
  • If the operand is a non-empty string, false is returned.
  • Returns true if the operand is the value 0.
  • Return false if the operand is a non-zero value (including Infinity).
  • If the operand is null, true is returned.
  • Returns true if the operand is NaN.
  • Returns true if the operand is undefined.

Use two exclamation points (!!) at the same time The equivalent of calling the transformation function Boolean()

3.7.4.2 Logic &&

Rules:

  • If the first operand is an object, return the second operand.
  • If the second operand is an object, the object is returned only if the first operand evaluates to true.
  • If both operands are objects, return the second operand.
  • If one of the operands is NULL, null is returned.
  • NaN is returned if one of the operands is NaN.
  • Returns undefined if one of the operands is undefined.

The logical and operator is a short-circuit operator, meaning if the first operand determines the result

3.7.4.3 logic or | |

Rules:

  • Returns the first operand if the first operand is an object.
  • If the first operand evaluates to false, the second operand is returned.
  • If both operands are objects, return the first operand.
  • If both operands are null, null is returned.
  • If both operands are NaN, NaN is returned.
  • If both operands are undefined, undefined is returned.

Logic or operators are also short-circuited, except that the second operand is not evaluated if the first operand evaluates to true

3.7.5 Multiplier operator

3.7.5.1 Multiplication operator *

  • If the operands are both numeric, the usual multiplication is performed, that is, two positive values multiplied together are positive, two negative values multiplied together are positive, and values with different signs multiplied together are negative. If ECMAScript cannot represent a product, Infinity or -infinity is returned.
  • NaN is returned if any of the operands is NaN.
  • If it’s Infinity times 0, NaN is returned.
  • If Infinity is multiplied by a finite number that is not zero, Infinity or -infinity is returned based on the sign of the second operand.
  • If it’s Infinity times Infinity, it returns Infinity.
  • If you have an operand that is not a value, you convert it to a value behind the scenes with Number() before applying the above rules.

3.7.5.2 Division operator /

  • If the operands are both numeric, then the normal division operation is performed, that is, two positive values divided by two negative values are positive, and two negative values divided by different signs are negative. If ECMAScript cannot represent quotient, Infinity or -infinity is returned.
  • NaN is returned if any of the operands is NaN.
  • If it’s Infinity divided by Infinity, it returns NaN.
  • If it’s 0 divided by 0, NaN is returned.
  • If a nonzero finite value is divided by 0, Infinity or -infinity is returned based on the sign of the first operand.
  • If Infinity is divided by any number, Infinity or -infinity is returned based on the sign of the second operand.
  • If you have an operand that is not a Number, you convert it to a Number behind the scenes using the Number() function before applying the above rules.

3.7.5.3 Module fetch operator %

  • If the operand is numeric, a normal division operation is performed, returning the remainder.
  • If the dividend is infinite and the divisor is finite, NaN is returned.
  • If the dividend is finite and the divisor is 0, NaN is returned.
  • If it’s Infinity divided by Infinity, it returns NaN.
  • Returns the dividend if the dividend is finite and the divisor is infinite.
  • If the dividend is 0 and the divisor is not 0, 0 is returned.
  • If you have an operand that is not a Number, you convert it to a Number behind the scenes using the Number() function before applying the above rules.

3.7.6 Index operator **

ECMAScript 7 adds the index operator, math.pow () now has its own operator **

console.log(Math.pow(3.2); / / 9
console.log(3支那2)         / / 9
Copy the code

3.7.7 Additive operators

The addition and subtraction operators

3.7.7.1 Addition operator +

Rule for adding both operands as numbers:

  • NaN is returned if any of the operands is NaN
  • If it’s Infinity plus Infinity, Infinity is returned
  • If it’s -infinity plus -infinity, it returns -infinity
  • If Infinity plus -infinity, NaN is returned
  • If it’s +0 plus +0, it returns +0
  • If it’s -0 plus +0, it returns +0
  • If it’s -0 plus -0, it returns -0

One of the operands is the string addition rule:

  • If both operands are strings, the second string is concatenated to the first string
  • If only one operand is a string, the other operand is converted to a string and the two strings are concatenated

3.7.7.2 Subtraction operator –

Subtraction operation rules:

  • If both operands are numeric, mathematical subtraction is performed and the result is returned
  • NaN is returned if any of the operands is NaN
  • If Infinity minus Infinity, NaN is returned
  • If it is -infinity minus -infinity, NaN is returned
  • If it’s Infinity minus -infinity, it returns Infinity
  • If it’s -infinity minus Infinity, it returns -infinity
  • If it’s +0 minus +0, it returns +0
  • If it is +0 minus -0, it returns -0. \ color {red} {????? }???
  • If it’s -0 minus -0, it returns +0
  • If any of the operands is a string, Boolean, null, or undefined, it is converted to a value behind the scenes using Number(), and then the math is performed according to the previous rules. If the result of the transformation is NaN, the result of the subtraction calculation is NaN.
  • If any of the operands is an object, the valueOf() method is called to get the value representing it. If the value is NaN, the result of the subtraction calculation is NaN. If the object does not have a valueOf() method, its toString() method is called and the resulting string is then converted to a value

3.7.8 Relational operators

Relational operators perform operations that compare two values, including less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=), all returning Boolean values.

Rules:

  • If the operands are all numeric, a numeric comparison is performed.
  • If the operands are all strings, the encoding of the corresponding character in the string is compared one by one.
  • If any of the operands is a value, the other operand is converted to a value and a numeric comparison is performed.
  • If any of the operands are objects, the valueOf() method is called, and the comparison is performed according to the previous rules after the result is obtained. If there is no valueOf() operator, the toString() method is called and the comparison is performed according to the previous rules after the result is obtained.
  • If any of the operands is a Boolean, it is converted to a numeric value before the comparison is performed.

When NaN comparisons are less than or greater than or equal to, the result of the comparison returns false.

3.7.9 Equality Operator

3.7.9.1 Equal and Do not Equal ==! =

Both operators perform a cast (often called a cast) before determining whether the operands are equal.

Conversion type rule:

  • If any of the operands is a Boolean, it is converted to a value and then compared for equality. False converts to 0 and true converts to 1.
  • If one of the operands is a string and the other is a value, it tries to convert the string to a value and then compares for equality.
  • If one operand is an object and the other is not, the valueOf() method of the object is called to get its original value, which is then compared according to the previous rules.

Comparison rules:

  • Null is equal to undefined.
  • Null and undefined cannot be converted to other types of values for comparison.
  • If any of the operands is NaN, the equality operator returns false and the inequality operator returns true. Remember: Even if both operands are NaN, the equality operator returns false because NaN is not equal to NaN by rule.
  • If both operands are objects, they are compared to see if they are the same object. The equality operator returns true if both operands refer to the same object. Otherwise, the two are not equal.

3.7.9.2 Congruence and incongruence ===! = =

Operands are not converted when congruent and incongruent operators compare.

Equal and not equal, perform type conversion before comparison. Congruent and incongruent, no type conversion is performed before comparison.

3.7.10 Conditional operators

variable = boolean_expression ? true_value : false_value;

3.7.11 Assignment operator =

Simple assignments are represented by the equals sign (=), which assigns the value of the right-hand side to the variable on the left-hand side

Compound assignment is indicated by a multiplicative, additive, or bitwise operator followed by an equals sign (=)

3.7.12 Comma operator,

  • Declaring multiple variables simultaneously in a single statement is the most common scenario for the comma operator
    let num1 = 1, num2 = 2, num3 = 3;
    Copy the code
  • Using the comma operator to separate values during assignment eventually returns the last value in the expression
    let num = (5.1.4.8.0); // the value of num is 0
    Copy the code

3.8 the statement

Ecma-262 describes statements (also known as flow control statements) in which most of the syntax in ECMAScript is expressed.

3.8.1 if statement

if (condition) statement1 else statement2
Copy the code

3.8.2 do – while statement

A do-while statement is a post-test loop in which the exit condition is evaluated only after the code in the body of the loop executes.

3.8.3 while statement

A while statement is a test-loop statement that checks the exit condition before executing the code inside the loop. Therefore, the code inside the while loop might not execute.

3.8.4 for statement

The for statement is also a test-first statement, but adds initialization code before entering the loop and expressions to execute after the loop executes.

for (initialization; expression; post-loop-expression) statement
Copy the code

3.8.5 the for in statement

A for-in statement is a strictly iterative statement that enumerates non-symbolic key attributes in an object.

for (property in expression) statement
Copy the code
  • Properties of objects in ECMAScript are unordered, so for-in statements do not guarantee the order in which object properties are returned.
  • If the for-in loop iterates over a variable that is null or undefined, the body of the loop is not executed.

3.8.6 for – statement

A for-of statement is a strict iteration statement that iterates through the elements of an iterable.

for (property of expression) statement
Copy the code
  • The for-of loop iterates over the elements in the order in which the iterable’s next() method produces the values.
  • Iterated variables do not support iteration, and the for-of statement throws an error.

ES2018 extends for-of statements by adding for-await-of loops to support asynchronous iterables that generate promises

3.8.7 Label Statements

Label statements are used to label statements

Grammar:

label: statement
Copy the code

Case study:

start: for (let i = 0; i < count; i++) {
    console.log(i);
}
Copy the code

Start is a label that can be referenced later with a break or continue statement. A typical use of label statements is nested loops.

3.8.8 Break and continue statements

The break and continue statements provide tighter control over the execution of loop code.

  • Break: Immediately exits the loop, forcing the next statement after the loop.
  • Continue: Exits the loop immediately and executes again from the top of the loop.
  • Both break and continue can be used with label statements.

Break and label statements example:

let num = 0;

outermost:
for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
        if (i == 5 && j == 5) {
            break outermost; // Exit the loop immediately and force the next statement after the loop.} num++; }}console.log(num); / / 55
Copy the code

Continue and label statements example:

let num = 0;

outermost:
for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
        if (i == 5 && j == 5) {
            continue outermost; // Exit the loop immediately and start executing again from the top of the loop.} num++; }}console.log(num); / / 95
Copy the code

3.8.9 with statement

The purpose of the with statement is to set the code scope to a specific object.

Grammar:

with (expression) statement;
Copy the code

Case study:

with(location) {
    let qs = search.substring(1);
    let hostName = hostname;
    let url = href;
}
Copy the code
  • Strict mode does not allow the with statement, otherwise an error will be thrown.
  • The with statement affects performance and makes it difficult to debug the code in it, and is generally not recommended for production code.

3.8.10 switch statement

The switch statement is a flow-control statement closely related to the IF statement, borrowed from other languages.

  • To avoid unnecessary condition judgments, it is best to follow each condition with a break statement.
  • Switch statements can be used for all data types.
  • The value of a condition does not need to be a constant; it can also be a variable or an expression.

The switch statement uses the congruent operator when comparing the value of each condition, so it does not cast the data type (for example, the string “10” does not equal the value 10).

3.9 the function

Functions are a core component of any language because they can encapsulate statements and execute them anywhere, at any time. Functions in ECMAScript are declared using the function keyword, followed by a set of parameters, followed by the function body.

function functionName(arg0, arg1,... ,argN) {
  statements
}
Copy the code
  • Any function can use a return statement at any time to return the value of the function, followed by the value to be returned.
  • A return statement can also have no return value. At this point, the function immediately stops execution and returns undefined. This is most often used to prematurely terminate function execution, not to return a value.

Strict mode also has some restrictions on functions:

  • Functions cannot be named eval or arguments
  • Function arguments cannot be called eval or arguments
  • Two named parameters cannot have the same name

3.10 summary

The core language features of JavaScript are defined in ECMA-262 in the form of the pseudo-language ECMAScript. ECMAScript contains all the basic syntax, operators, data types, and objects that perform basic computational tasks, but does not provide a mechanism for getting input and producing output. Understanding ECMAScript and its complex details is key to fully understanding JavaScript in a browser. Here’s a summary of the basic elements in ECMAScript.

  • Basic data types in ECMAScript include Undefined, Null, Boolean, Number, BigInt(ES11), String, and Symbol.
  • Unlike other languages, ECMAScript does not distinguish between integer and floating point values, and has only one numeric data type, Number.
  • Object is a complex data type that is the base class for all objects in the language.
  • Strict patterns impose restrictions on certain error-prone parts of the language.
  • ECMAScript provides many of the basic operators found in C and C-like languages, including mathematical, Boolean, relational, equality, and assignment operators.
  • The flow control statements in this language are mostly borrowed from other languages, such as if statements, for statements, and switch statements.

Functions in ECMAScript are different from functions in other languages.

  • There is no need to specify the return value of a function, because any function can return any value at any time.
  • Functions that specify a return value actually return the special value undefined.