grammar

ECMAScript’s syntax borrows heavily from C and other C-like languages such as Java and Perl. As a result, developers familiar with these languages should feel at ease when accepting ECMAScript’s looser syntax.

Case sensitive

Everything in ECMAScript is case sensitive, such as function names, variable names, operators, etc.

  • Fun() and fun() are two different functions
  • Test and test are two different variable names

identifier

Identifiers refer to variable names, function names, attribute names, parameter names and other identifiers in ECMAScript. Identifiers are named as follows

  • The first character must be a letter, underscore (_), and a dollar sign ($).
  • Other characters must be: letters, digits, underscores (_), dollar signs ($)
  • By convention, when naming identifiers in ECMAScript, we try to use camelback nomenclature, where the first letter of the first word is lowercase and the following words are uppercase
  • You cannot use reserved words and keywords as identifiers’ names

annotation

  • Single-line comment: // This is a single-line comment
  • Multi-line comment: /* This is a multi-line comment */

Strict Mode

Strict mode, introduced in ECMAScript 5, defines a completely different parsing and execution model for JavaScript, where certain unsafe operations throw errors

  • Use strict mode in global mode:
    "use strict";   // Add it at the top of the script file
    function name(){... }Copy the code
  • Use strict patterns inside functions:
    function name(){
        "use strict";    // Use strict mode inside functions. }Copy the code

statements

Statements in ECMAScript end with a semicolon; if the semicolon is omitted, it is up to the parser to determine the ending

    var sum = a + b     // This works even without a semicolon, but is not recommended
    var diff = a - b;   / / recommend
Copy the code

Advantages of using semicolons:

  • To avoid mistakes
  • You can’t make mistakes with compressed code
  • Increase the performance of your code

If there are multiple pieces of code, they must be wrapped in code blocks

    if (test){          // If there is only one statement in the code block, it is not recommended to omit the code block
        test = false;
        alert(test);
    }
Copy the code

Benefits of using code blocks:

  • Identify what part of the code belongs to
  • Avoid errors in modifying code

Keywords and reserved words

Keywords are a set of characters in ECMA262 that have a specific purpose. They may be used to control the start and end of a statement or to perform a specific operation

Reserved words are reserved words that may be used as keywords in the future

Neither keyword nor reserved word can be used as an identifier

variable

Variables in ECMAScript are loosely typed and can be used to hold any type of data; each variable is just a placeholder to hold a value

Define variables:

    var name    /// use the var operator followed by a variable name to define a local variable
Copy the code
  • A variable like this, which is just defined and not initialized, will hold a special value -undefined by default
  • Initialization is assigning a value to a variable
  • ECMAScript supports assigning values to variables at the same time as defining them, and the type of the value can be changed at the same time as the value of the variable
    var message = "hi";     // Declare the variable message and initialize it to "hi"
    message = 10;           // Modify the value and value type (string->number)
    The above actions are fully valid in ECMAScript, but are not recommended
Copy the code
  • Variables defined using the var operator will become local variables in the current scope
  • A local variable created inside a function that is generated when the function is called and destroyed when the function is finished running
    function test(){
        var message = "hi"; // Message is a local variable under test
    }
    alert(message);         // The browser reported an error, the variable does not exist
Copy the code
  • Variables created by omitting the var operator are global variables, but this is not recommended because it is difficult to maintain
    function test(){
        message = "hi";
    }
    alert(message);         / / get the "hi"
Copy the code
  • You can define multiple variables in a single statement, but use commas to separate each variable
    function test(){    Num1, num2, num3
        var num1,       // only declare (undefined)
            num2 = 1.// Declare and initialize (1)
            num3;       // undefined
    }
    function test2(){
        var num1 = num2 = num3 = 1;
        // This declaration also generates three variables, but only two global and one local
        // Is equivalent to the following statement
        num3 = 1;       // global num3
        num2 = num3;    // global num2
        var num1 = num2;// local variable num1
    }
Copy the code

The data type

ECMAScript has five simple data types (basic data types) : Undefined, Null, Boolean, Number, String. In addition to simple data types, there is another complex data type: Object, which is essentially an unordered set of key-value pairs.

The typeof operator

Because ECMAScript is loosely typed, you need a way to detect the data typeof a variable, and the typeof operator does just that.

Using the Typeof operator on a variable yields the following string:

  • “Undefined” – If the value is undefined or uninitialized
  • “Boolean” – If the value is a Boolean
  • “String” – if the value is a string
  • “Number” – if the value is numerical
  • “Object” – If the value is an object or null
  • “Function” – if the value is a function

Here are some examples of using typeof operators

    function test(){
        alert(typeof "String");     // "string"
        alert(typeof ("String"));   // "string"
        alert(typeof 24);          // "number" 
    }
Copy the code

Note that typeof is an operator, not a function, and it can be followed by a parenthesis, but this is not required

Undefined type

Undefined has only one value, which is the special Undefined

  • When we declare a variable using var but do not initialize it, the value of the variable is undefined by default

  • A variable whose value is undefined is not the same as an undefined variable. Undefined variables cannot be operated on

  • Undefined can perform only one operation, which is to type it with the Typeof operator

    function test(){
        var message;        // Declare variables but do not initialize them. Default is undefined
        
        alert(message);     // "undefined"
        alert(age);         // "age is not defined"
    }
Copy the code
  • However, undefined is returned when operating on undefined and uninitialized variables using the Typeof operator
    function test(){
        var message;
        
        alert(typeof message);  // "undefined"
        alert(typeof age);      // "undefined"
    }
Copy the code

Null type

The Null type has only one value, which is the special Null

  • Null represents an empty object pointer, so “object” is returned when typeof is used to detect it.
  • If you define a variable that will be used to store complex data types (objects), it is best to initialize it to NULL
  • Undefined is derived from null, so testing with the equality operator returns true
    function test(){
        alert(null= =undefined);   // "true"
    }
Copy the code

Boolean type

The Boolean type is the most commonly used type in ECMAScript and has only two literals: true and false

  • Boolean literals are case sensitive. Only true and false are Boolean types. Others, such as true and false, are only identifiers and are not Boolean data types
  • All types of ECMAScript values can be converted to corresponding Boolean values by calling the transition function Boolean()
The data type The value converted to true Convert to a value of false
Boolean true false
String Any non-empty string “”
Number Any number that is not zero 0/NaN
Object Any object null
Undefined N/A (not applicable) undefined

The Number type

ECMAScript’s Number type uses the IEEE754 format to represent integer and floating point values (double precision values)

  • The most basic numeric literal format is the decimal integer
  • In addition to decimal, integers can also be represented in octal and hexadecimal
    • The first digit of an octal literal must be 0, followed by a sequence of octal digits (0 to 7)
    • The hexadecimal literal must begin with 0x, followed by A series of hexadecimal digits (0 to 9 and A to F) that are case-insensitive
    • Those that do not meet the above conditions are expressed in decimal notation
  • In arithmetic, all values are converted to decimal values for calculation

Floating point value

A floating point value must contain a decimal point and must be followed by at least one digit

  • Since saving floating-point values requires twice as much memory as saving integer values, ECMAScript loses no time converting floating-point values to integer values
    • If there is no number behind the decimal point, the value is converted to an integer
    • If the float itself represents an integer (such as 1.0), the value is also converted to an integer
  • By default, ECMAScript converts floating point values with more than six zeros after the decimal point to a value in e notation (e.g. 0.0000003 is converted to 3E-7 (3 * 10^-7))
  • Floating-point values have a maximum accuracy of 17 decimal places, but they are far less accurate than integers when doing arithmetic, for example, 0.1 + 0.2 is not 0.3
    var num = 0.1 + 0.2;
    alert(num === 0.3);     // false
Copy the code
  • The problem of error in floating-point calculations is a common problem with IEEE754 based floating-point calculations in all languages using the IEEE754 format

Numerical range

Due to memory limitations, ECMAScript does not save all the values in the world

  • The minimum value that ECMAScript can represent is stored in number.min_value and the maximum value that ECMAScript can represent is stored in number.max_value
  • If the calculated value exceeds the above range of values, the value is automatically converted to a special value Infinity
    • If the value is negative, it will be converted to -infinity.
    • If this value is positive, it will be converted to Infinity.
    • A positive number divided by 0 returns Infinity
    • A negative number divided by 0 returns -infinity
  • If the result returns a positive or negative Infinity value in one calculation, the value will not be evaluated in the next calculation. Infinity is not a computable value
  • If we want to know if a number is computable, we can use isFinite(), which returns true if the parameter is a computable number
    function test(){
        alert(isFinite(Number.MAX_VALUE));   // false
        alert(isFinite(Number.MIN_VALUE));   // false
        alert(isFinite(1));                  // true
    }
Copy the code

NaN

NaN is Not a Number is a special value that indicates if an operation that was supposed to return a Number does Not return a Number (so that no error is thrown)

  • In ECMAScript, any number divided by a non-number (which cannot be converted to a number) returns NaN, as does 0 divided by 0
  • NaN itself has two characteristics
    • Any operation or calculation that involves a NaN returns a NaN
    • NaN is not equal to any value, including NaN itself
  • If we want to know if the value of a variable isNaN, we can use the isNaN() function, which can take any type of value. When isNaN() receives an argument, it converts the argument. If it cannot convert to a value, Will return true
    function test(){
        alert( isNaN(10));// "false"
        alert( isNaN("string"));// "true"
        alert( isNaN(true));// "false" (can be converted to value 1)
    }
Copy the code

Numerical transformation

In ECMAScript, there are three functions that convert non-numeric values to numeric values: Number(), parseInt(), parseFloat()

  • Number() can be used to convert any data type, and the other two functions are dedicated to converting strings to numbers
  • Conversion rule for Number() :
    • If Boolean, true and false will be converted to 1 and 0, respectively
    • If it’s a Number value, it’s simply passed in and out
    • If Null, 0 is returned
    • Returns NaN if undefined
    • If it is a string:
      • If it is an empty string, return 0
      • If the string contains only numbers and is a valid hexadecimal value, convert to a decimal integer value of the same size
      • If the string contains only numbers (including the leading plus and minus signs), convert to a decimal integer, ignoring the leading 0 (“011” is converted to 11)
      • If the string has only digits and a decimal point and is a valid floating-point value format, convert to a floating-point value, ignoring the leading 0 (“01.1” will be converted to 1.1)
      • If not, return NaN if it is an object:
      • Call the valueOf() method of the object, and then convert the returned value according to the previous rules. If the converted value is NaN, call the toString() method of the object, and then convert the returned string according to the previous rules
  • ParseInt () conversion rule:
    • Ignore whitespace before the string until the first non-whitespace character is found
    • If the first character is not a number, parseInt() returns NaN
    • That is, converting an empty string with parseInt() or a string that begins with a non-number returns NaN (Number() and converting an empty string returns 0)
    • If the first character of the string is a numeric character, parseInt() continues parsing the string until either the string is parsed or a non-numeric character is encountered
    • The parseInt() function recognizes numeric characters in octal, decimal, and hexadecimal formats
    • The second argument to parseInt() can specify the base to use when converting
        function test(){
    
            var num = parseInt("0xAF".16);         // Specify hexadecimal, return 175
    
            var num1 = parseInt("0xAF".10);        // Specify decimal, return 0
    
        }
    Copy the code
    • Not specifying cardinality means leaving it up to parseInt() to decide how to parse the input string. Should we specify cardinality explicitly in any case to avoid incorrect parsing
  • Conversion rules for parseFloat()
    • Similar to the parseInt() rule, but with a few differences
    • The decimal point is a valid floating point numeric character in the parseFloat() method, but only the first decimal point is valid
    • ParseFloat () recognizes all floating-point numeric formats, but it only parses decimal values, so it ignores leading zeros and hexadecimal numeric characters are recognized as zeros
    • ParseFloat () parses only decimal numeric characters, so there is no second argument to specify the cardinality to parse

Type String

The String type represents a sequence of zero or more 16-bit Unicode characters, known as strings. Strings can be expressed in single or double quotation marks

  • Character literals:

    • The String data type contains special character literals, also called transition sequences, that are used to represent non-print characters, or characters that have other uses
    • Here are some common character literals:
    literal meaning
    \ 0 Null character
    \n A newline
    \ \ slash
    \ ‘ Single quotes
    \” Double quotation marks
    • A character literal can appear anywhere in the string and will also be parsed as a character
  • Characteristics of strings

    • Strings in ECMAScript are immutable; once strings are created, their values cannot be changed
    • If you want to change a string stored in a variable, you first destroy the original string and then populate the variable with another string containing the new value
  • Convert to string

If we want to convert a value to a String, we can use the toString() method, which is available for almost all values, and the String() function, which is available for all values

  • ToString () method:
    • Number, Boolean, Object, and String all have a toString() method. The rest of the Null and Undefined types do not. So null and undefined call toString() will return an error
    • Values of type Number can be passed with the toString() method, which by default returns a string representation of the value in decimal format
    • ToString () can output string values in binary, octal, hexadecimal, or any other valid base format
  • String () function
    • If you don’t know whether the value to be converted is null or undefined, you can use the String() function, which converts all types of values to strings
    • If the value has a toString() method, call it (with no arguments)
    • If this value is null, return null
    • If the value is undefined, return undefined

The Object type

An object in ECMAScript is simply a collection of data and functionality

  • We can create an instance of type Object with the new operator and add attributes and methods to it
    function test(){
        var obj = new Object( );        // Create an instance of type object
        var obj1 = new Object;
        // If we do not pass any arguments when creating the instance object, the following parentheses can be omitted, but this is not recommended
    }
Copy the code
  • In ECMAScript, the Object type is a constructor for all instance objects, all of which have Object properties and methods
    • Constructor: Holds the function (constructor) used to create the current object
    • HasOwnProperty (propertyName) : Checks if a given property exists in the current instance object (not in the prototype of the instance) and the argument must be a string
    • PropertyIsEnumerable (propertyName) : Checks if a given property can be enumerated in a for-in statement. The argument must be a string
    • IsPrototypeOf (object) : Used to check whether the incoming object is a prototype of the current object
    • ToLocaleString () : Returns a string formed by concatenating the generated strings using locale-specific separators, that is, a string with a format, such as 1234 to 1,234, and standard time to local time.
    • ToString () : Returns a string representation of an object
    • ValueOf () : Returns a string, numeric, or Boolean representation of an object, usually the same value as the toString() method

The operator

Ecma-262 describes a set of operators for manipulating data values, including arithmetic operators (such as add and subtract), bitwise operators, relational operators, and equality operators

Unary operator

Only one worth operator can be operated on, called the unary operator

  • Increment and decrement operators
    • The increment and decrement operators have both pre – and post-type, which are directly borrowed from C
    • Pre – type: first add one, then calculate the whole
    • Postposition: calculates the whole first and then adds one to itself
    • Increment operator
        function test(){
            var age = 23;
            var num = 2;
            alert(++age + num);     // Add one to self, output 26
            alert(age);             / / 24
        }
        function test1(){
            var age = 23;
            var num = 2;
            alert(age++ + num);     // The output is 25
            alert(age);             / / 24
        }
    Copy the code
    • The decrement operator is similar to the increment operator
  • The increment and decrement operators apply to any value, except integers, but also to strings, Bools, floating-point values, and objects
    • When a value is used with the increment or decrement operators, the value is first converted to a value of type Number, and then the evaluation operation is attempted
    • If a string contains only numbers, the string is converted to numeric values and then evaluated
    • If a string contains characters other than numbers, the string is converted to NaN
    • If it is a Boolean value, true is converted to 1 and false to 0
    • If it is a floating point value, the calculation is performed directly
    • In the case of an object, the valueOf() method of the object is called and returns an operable value. If the operation returns NaN, the preceding rule applies after the toString() method is called
    • All types are converted to the Number type
  • Unary addition and subtraction operators
    • The unary addition operator, represented by a plus sign (+), precedes the value and has no effect on the value
    • The unary subtraction operator, represented by a minus sign (-), precedes a number and is used primarily to represent negative numbers
    • For non-numeric values, the unary addition and subtraction operators first convert the value using the Number() transformation function
    • The unary addition and subtraction operators are used primarily for basic arithmetic operations and can also be used to convert data types

Boolean operator

  • No matter what data type the value is, the Boolean operator first converts it to a Boolean value using the Boolean() transformation function
  • Logic is not
    • Logical non-operators consist of an exclamation mark (!). Can be applied to any value in ECMAScript
    • Logic is not just a simple inverse Boolean. You can also use two exclamation marks to get the Boolean value of the current value, equivalent to using the Boolean() function
  • Logic and
    • Logic and operators are represented by two ampersand signs (&&) and have two operands
    • Logic and is a short-circuit operator:
      • If the first operand has a Boolean value of false, the logic and operator returns the first operand and does not evaluate the second
      • If the first operand has a Boolean value of true, the logic and operator return the second operand
  • Logic or
    • Logic or the operator by two vertical lines minus (| |), said there are two operands
    • Logic may also be a short-circuit operator:
      • If the first operand has a Boolean value of true, the logic or operator returns the first operand and does not evaluate the second
      • If the first operand has a Boolean value of false, the logic or operator returns the second operand
  • The short-circuit operator, in short, returns the operand that determines the final result
    • Boolean and: Returns false as long as there is a false, so as long as the first operand is false, the result must be false
    • Boolean or: As long as there is a true, the return Boolean is true, so as long as the first operand is true, the result must be true

Multiplicative operator

ECMAScript defines three multiplicative operators: multiplication, division and mod.

  • These operators automatically call the Number() function to perform type conversions if the operands are non-numeric
  • Multiplication: Multiplication is indicated by an asterisk (*) and is used to compute the product of two numerical values
  • In the case of special values, the multiplication operator follows the following rule:
    • If the operands are all numeric, then normal multiplication is performed, and if the product exceeds the maximum value range, Infinity or -infinity is returned
    • If one of the operands is NaN, return NaN
    • If Infinity is multiplied by 0, NaN is returned
    • If you multiply Infinity times a non-zero number, you get Infinity or -infinity, depending on how positive or negative the non-zero number is
    • If you multiply Infinity by Infinity, you return Infinity
    • If the operand is not a Number, call the Number() function to convert it to a Number, and then apply the above rules
  • Division: A division, represented by a slash (/), performs the calculation of the second operand divided by the first
  • In the case of special values, the division operator follows the following rules:
    • If the operands are all values, then normal division is performed, and if the quotient exceeds the maximum value range, Infinity or -infinity is returned
    • If one of the operands is NaN, return NaN
    • If Infinity is divided by Infinity, NaN is returned
    • If zero is divided by zero, NaN is returned
    • If a finite non-zero value is divided by zero, return Infinity or -infinity
    • If Infinity is divided by any non-zero value, return Infinity or -infinity
    • If the operand is not a Number, call the Number() function to convert it to a Number, and then apply the above rules
  • Mod: The mod operator is represented by a percent sign (%). The remainder of the first operand is divided by the second operand
  • Like the other two multiplicative operators, in the case of special values, the mod operator follows the following rules:
    • If the dividend is infinitely large and the divisor is finite, NaN is returned
    • If the dividend is finitely large and the divisor is zero, NaN is returned
    • If Infinity is divided by Infinity, return NaN
    • Returns the dividend if the dividend is finitely large and the divisor is infinitely large
    • If the dividend is zero, return zero
    • If the operand is not a Number, call the Number() function to convert it to a Number, and then apply the above rules

The additive operator

  • add
    • If it’s Infinity plus -infinity, return NaN
    • If one of the operands is a string, the other operand is converted to a string, and then the string is concatenated
    • If the operands are all strings, concatenate the strings
  • subtraction
    • If Infinity minus Infinity, return NaN
    • If it’s -infinity minus -infinity, return NaN
    • If you have an operand that is not of a numeric type, use the Number() function to convert the string to a numeric value, and then evaluate

Relational operator

Relational operators return booleans. There are four types of operators: less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=).

  • If both operands are numeric, compare the sizes normally
  • If one of the operands is numeric and the other is of a non-numeric type, convert it to numeric and then compare the sizes
  • If both operands are strings, compare the character encoding values of the two strings
  • If one of the operands is a Boolean, convert to a numeric value and compare the size
  • If it is an object, call the valueof() method and then compare the size, or if the object has no valueof() method, call the toString() method and then compare the size
  • A NaN comparison with any operand returns false

Equality operator

  • Equal and unequal: Convert first and then compare
    • The equality operator is represented by two equal (==) signs and returns true if the operands are equal
    • The unequal operator consists of an exclamation mark and an equal sign (! =), returns true if the operands are not equal
    • Both operators first cast the operand’s data type (forced cast) and then compare their equality
    • Conversion rules:
      • If one of the operands is a Boolean, convert to a numeric number, where true is 1 and false is 0
      • If one of the operands is a string and the other is a number, convert the string to a number
      • If one operand is an object and the other is not, call the valueOf() method of the object and use the resulting primitive data types to make the above comparison
    • Null, undefined, and NaN
      • Null and undefined are equal but not congruent
      • Null and undefined cannot be converted to any value
      • If one of the operands is NaN, the equality operator returns false and the inequality operator returns true. NaN is not equal to any number, including NaN itself
      • The equality operator returns true if both operands are objects and if both refer to the same object
  • Congruence and incongruence: comparison only, not conversion
    • The congruence operator is represented by three equal signs (===) and returns true if the two operands are equal
    • The unequal operator consists of an exclamation mark and two equal signs (! ==) returns true if the operands are not equal
    • These two operators compare the two operands directly without converting the data type

Conditional operator

Conditional operators are one of the most flexible operators in ECMAScript, and they follow the same syntactic form as conditional operators in Java

    var num1,num2...
    function test(){
        var max = (num1 > num2) ? num1 : num2;
        // If num1 is greater than num2, return true to assign num1 to Max and false to assign num2 to Max
    }
Copy the code

The assignment operator

  • The simple assignment operator, represented by the equals sign (=), assigns the value on the right to the variable on the left
    function test(){
        var num = 1;
    }
Copy the code
  • The complex assignment is to add the multiplicative, additive, and bitwise operators before the equals sign
    function test(){
        var num = 1;
        num += 1;       // is the same as num = num + 1, other complex assignments are similar, just replace the plus sign
    }
Copy the code
  • The purpose of these complex operators is to simplify assignment operations, and there is no performance gain from using them

Comma operator

  • The comma operator allows you to perform multiple operations in a single statement, often to declare multiple variables
    function test(){
        var num1 = 1, num2 = 2, num3;
    }
Copy the code
  • The comma operator can be used for assignment, which returns the last item of an expression
    function test(){
        var num = (1.2.3);      // num === 3
    }
Copy the code

statements

Statements, also known as flow control statements, typically use one or more keywords to accomplish a given task

If statement

    function test(){
        if ( Boolean) {// Use Boolean values in parentheses to control code execution
            // do something... // Code executed when Boolean is true
        } else{
            // do something... // Code executed when Boolean is false
        }                           // A block of code is essential, even if it is only one line
    }
Copy the code

Do – while statement

A post-loop statement that terminates the loop if the condition is false, and no matter what the condition is, it must execute the code once, okay

    function test(){
        do {                        // Test the loop statement after
            // do something... // Execute the code first
        } while( Boolean );         // determine the condition
    }
Copy the code

While statement

If the condition value is false, the loop is terminated. If the condition value is false, the code is executed. If the condition value is false, the loop body is skipped and the next operation is performed

    function test(){
        while ( Boolean) {// Determine the condition first
            // do something... // Execute the code}}Copy the code

For statement

The for statement is also a pre-loop statement. It is another form of the while statement, which can be seen as putting the code of the while statement in one place

    function test(){
        for (var i = 1; i < 10; i++){
            // do something...
        }
        /* This code is equivalent to the following while statement */
        var i = 1;
        while (i < 10) {// do something...i++; }}Copy the code
  • A for statement cannot do what a while statement cannot do
  • In ES5, there is no block-level scope, so variables declared in the for statement can be accessed outside of the for statement (variables declared with var are local variables, variables not declared with var are global variables).
  • You can create an infinite loop by omitting the expression in the for loop
    function test(){
        for(;;) {// This is an infinite loop
            // do something...}}Copy the code

The for in statement

A for-in statement is a precise iteration statement that can be used to enumerate the properties of an object

    var obj = {
        name : "oswald".age : 24
    };
    for (var propName in obj){  // Iterate over all attributes in obj
        alert(propName);        // "name" "age"
        alert(obj[propName]);   // "oswald" "24"
    }
Copy the code
  • Interrupt execution is reported when the attribute value is null or undefined, so it is best to check for null and undefined before executing a for-in statement
  • Similar to the for-in statement, variables declared in for-in statements can be accessed outside of for-in statements
  • Properties of ECMAScript objects are not ordered, so the order of property names looping through for-in statements is unpredictable. Although each property is returned once, the order of return may vary depending on the browser
  • It is not recommended to iterate over an array object through a for-in statement if the array is a sequential object

Break and continue statements

The break and continue statements are used to precisely control the execution of the code within the loop

    function test(){
        var num = 0;
        for (var i = 1; i < 10; i++){
            if(i % 2= = =0) {// If I === 2, the loop is broken out and the body of the loop is no longer executed
                break;                  
            }
            num++;
        }
        alert(num);   / / 1
    }
    function test2(){
        var num = 0;
        for (var i = 1; i < 10; i++){
            if(i % 2= = =0) {// If I === 2, this loop is skipped and the next loop is entered
                continue;
            }
            num++;
        }
        alert(num);   / / 5
    }
Copy the code

With statement

The with statement sets the scope of the code to a specific object

  • The with statement is not allowed in strict mode and is considered a syntax error
  • Excessive use of the with statement deteriorates performance and is difficult to maintain. Therefore, use the with statement is not recommended

A switch statement

The switch statement is the most closely related to the if statement, and is the flow control statement commonly used in other languages

    var i...
    function test(){
        switch(i){
            case 25 :
                alert("25");
                break;  
                // Break is used to break out of the current switch statement. If omitted, the next case will continue
            case 35 :
                alert("35");
                break;
            case 45 :
                // Merge two cases
            case 55 :
                alert("55");
                break;
            default :
                alert("other"); }}Copy the code
  • You can use any data type in a Switch statement, whether it’s a string or an object
  • The value of each case does not have to be a constant; it can be a variable or even an expression
  • Each case value can return a Boolean, and each case is evaluated in order until a match is found or a default statement is encountered
  • The switch statement uses the congruence operator when comparing values

function

Functions can encapsulate multiple arbitrary statements and can be called and executed from anywhere at any time

  • Functions in ECMAScript are declared using the function keyword, followed by a set of parameters and the function body
  • A function does not have to specify whether or not to return a value. Any function can return a value at any time through a return statement followed by the value to be returned
    function test(num1, num2){
        return (num1 + num2);       // Stop executing the function and return num1 + num2
        alert(num1);                // This operation will not be performed
    }
Copy the code
  • The function stops and exits immediately after the return statement, so no code is executed after the return statement
  • A statement can also contain multiple return statements
    function test(num1, num2){
        if(num1 < num2){
            return (num2 - num1);
        } else{
            return(num1 - num2); }}Copy the code
  • A return statement can also have no return value, so it will return undefined by default

Arguments in a function

  • Arguments in ECMAScript are internally represented by an array, which is always received by the function
  • We can access this array of arguments via the arguments object inside the function body to get each argument passed to the function
  • The Arguments object is just like an Array. It is not an instance of an Array object. You can use the square bracket syntax to access each of its elements and the length attribute to determine how many arguments are passed in
  • We can invoke arguments passed in using square brackets syntax, so named arguments are not required
    function sayHi(name, message){
        alert("Hello" + arguments[0] + "," + arguments[1]);
        /* The code above is the same as the one below */
        alert("Hello" + name + "," + message);  // Named parameters are convenience only, not required
        The length property of the // arguments object tells you how many arguments are passed to the function
        alert(arguments.length);                / / 2
    }
Copy the code
  • The values of the Arguments object are always in sync with the values of the named arguments
  • Named parameters with no passed value are automatically assigned undefined
  • All arguments in ECMAScript are passed as values and arguments[0] are not passed by reference. This means that while the name parameter and arguments[0] values in the above example are the same, they are two different memory Spaces and just keep the values the same. Same thing with objects
  • Because there is no function signature feature, ECMAScript functions cannot be overridden, but they can mimic method overloading by checking the type and number of arguments passed into the function and reacting differently