Chapter three, language foundation

This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

The core of any language describes how the language works at the most basic level, involving syntax, operators, data types, and built-in functionality, on which complex solutions can be built. As mentioned earlier, ECMA-262 defines all of these aspects of JavaScript in the form of a pseudo-language called ECMAScript.

3.1 grammar

ECMAScript’s syntax borrows heavily from C and other C-like languages such as Java and Perl. For developers familiar with these languages, ECMAScript’s loose syntax should be easy to understand. Even small white learning, is also very easy to understand

3.1.1 Case sensitive

The first thing to know is that everything in ECMAScript is case sensitive. Both variables, function names, and operators are case sensitive. In other words, the variables test and test are two different variables. Similarly, Typeof cannot be used as a function name because it is a keyword (described later). But Typeof is a perfectly valid function name.

3.1.2 identifier

An identifier is the name of a variable, function, property, or function parameter. An identifier may consist of one or more of the following characters:

  • The first character must be a letter, an underscore (_), or a dollar sign ($)
  • The remaining other characters can be letters, underscores, dollar signs, or numbers

The letters in the identifier can be the letters in Extended ASCII, or they can be Unicode alphabetic characters such as A and æ f (not recommended).

By convention, ECMAScript identifiers use camel case, meaning the first letter of the first word is lowercase and the first letter of each subsequent word is capitalized, as in:

firstSecond
myCar
doSomethingImportant
Copy the code

This isn’t mandatory, but it’s a best practice because it’s consistent with how ECMAScript’s built-in functions and objects are named. (In order to write elegant code, it is very important to make your code legible, so that people can understand what you write at a glance. In addition to naming conventions, writing conventions are also important.)

3.1.3 annotation

ECMAScript uses C-style comments, both single-line comments and block comments. Single-line comments begin with two slash characters, such as:

// Single-line comment block comments begin with a slash and an asterisk (/*) and end with their reverse combination (*/), such as: /* This is a multi-line comment */Copy the code

3.1.4 Strict mode

ECMAScript 5 adds the concept of strict Mode. Strict mode is a different JavaScript parsing and execution model in which some of ECMAScript 3’s irregularities are handled and errors are thrown for unsafe activities. To enable strict mode for the entire script, add this line at the beginning of the script:

"use strict";
Copy the code

Although it looks like a string that is not assigned to any variable, it is actually a preprocessor instruction. Any supported JavaScript engine that sees it will switch to strict mode. This syntax form was chosen so as not to break the ECMAScript 3 syntax.

It is also possible to specify a separate function to execute in strict mode by placing the preprocessor instruction at the beginning of the function body:

function doSomething() { "use strict"; // Function body}Copy the code

Strict mode affects many aspects of JavaScript execution, so it will be explicitly pointed out when used in this book. All modern browsers support strict mode.

3.1.5 statement

Statements in ECMAScript end in a semicolon. Omitting the semicolon means that it is up to the parser to determine where the statement ends, as shown in the following example:

Let sum = a + b; let diff = a + b; // Add semicolon valid, recommendedCopy the code

Semicolons at the end of statements should be added even if they are not required. Remember to add semicolons to help prevent problems with omission, such as incomplete input. In addition, the addition of semicolons also makes it easier for developers to compress code by removing empty lines (if there is no ending semicolon, deleting only empty lines will result in a syntax error). Adding semicolons can also help performance in some cases, as the parser tries to put semicolons in place to correct syntax errors.

Multiple statements can be combined into a Single C-style code block. The code block begins with an open curly brace ({) and ends with a close curly brace (}) :

if (test) {
    test = false;
    console.log(test);
}
Copy the code

Control statements such as if require a block of code only when multiple statements are executed. However, it is a best practice to always use code blocks in control statements, even if only one statement is executed, as in the following example:

If (test) console.log(test); If (test) {console.log(test); }Copy the code

Using blocks of code in control statements makes the content clearer and reduces the likelihood of an error if the code needs to be modified.

3.2 Keywords and Reserved Words

Ecma-262 describes a reserved set of keywords that have special uses, such as indicating the start and end of control statements, or performing specific operations. As a rule, reserved keywords cannot be used as identifiers or attribute names. All keywords specified in ecMA-262 6th edition 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
Copy the code

The specification also describes a set of future reserved words, which again cannot be used as identifiers or attribute names. Although reserved words have no specific use in the language, they are reserved for future keyword use.

Here are all the words reserved for the future in the 6th edition of ECMA-262.

Always retain:

enum
Copy the code

Reserved in strict mode:

implements package public
interface protected static
let private
Copy the code

In module code:

await
Copy the code

These terms cannot be used as identifiers, but can now be used as property names for objects. In general, it is best not to use keywords and reserved words as identifiers and attribute names to ensure compatibility with past and future versions of ECMAScript.

3.3 variable

ECMAScript variables are loosely typed, meaning that they can be used to hold any type of data. Each variable is nothing more than a named placeholder for holding any value. Variables can be declared with three keywords: var, const, and let. Var is available in all versions of ECMAScript, while const and let are available only in ECMAScript 6 and later.

3.3.1 the var keyword

To define a variable, use the var operator (note that var is a keyword), followed by the variable name (that is, the identifier, as described earlier) :

var message;
Copy the code

This line of code defines a variable called message, which can be used to hold any type of value. (When not initialized, variables hold a special value called undefined, which we’ll discuss in the next section when we discuss data types.) ECMAScript implements variable initialization, so you can define a variable and set its value at the same time:

var message = "hi";
Copy the code

Here, message is defined as a variable that holds the string value hi. Initializing a variable like this doesn’t identify it as a string, it’s just a simple assignment. Later, you can change not only the saved value, but also the type of the value:

var message = "hi"; message = 100; // Legal, but not recommendedCopy the code

In this example, the variable message is first defined as a variable that holds the string value hi, and then rewritten to hold the value 100. It is not recommended to change the type of variables that hold values, but it is fully valid in ECMAScript.

  1. Var declares scope

    The key problem is that a variable defined using the var operator becomes a local variable to the function that contains it. For example, using var to define a variable inside a function means that the variable will be destroyed when the function exits:

    function test() { var message = "hi"; // local variable} test(); console.log(message); / / error!Copy the code

    Here, the message variable is defined inside the function using var. The function is called test(), and calling it creates the variable and assigns it a value. The variable is destroyed immediately after the call, so the last line in the example results in an error. However, we can create a global variable by omitting the var operator when defining variables within a function:

    function test() { message = "hi"; // global} test(); console.log(message); // "hi"Copy the code

    After the previous var operator is removed, message becomes a global variable. The variable is defined once the function test() is called and can be accessed outside of the function. (Usually not)

    If you need to define more than one variable, you can separate each variable (and optionally initialize it) in a single statement with a comma:

    var message = "hi",
        found = false,
        age = 29;
    Copy the code

    There are three variables defined and initialized. Because ECMAScript is loosely typed, variables initialized with different data types can be declared in a single statement. It is not necessary to insert line breaks and indent Spaces, but it is good for reading comprehension.

    In strict mode, you cannot define variables named eval and arguments, as this would cause syntax errors.

  2. Var declaration promotion

    The following code does not report an error when using var. This is because variables declared with this keyword are automatically promoted to the top of the function scope:

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

    This does not happen because the ECMAScript runtime treats it as equivalent to the following code:

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

    This is called a “hoist,” which means pulling all variable declarations to the top of the function scope. In addition, using var multiple times to declare the same variable is not a problem:

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

I have already written nearly 3,000 words. The purpose of this series is to make use of fragmented time to read, and you will be tired of writing too much. The next part will talk about let and const, and data types and operators, which are very basic and fragmentary knowledge. Come on!!!!!!