Basic syntax of JavaScript

Statement

The execution unit of JavaScript program is line (line), that is, it is executed line by line. Under normal circumstances, each line is a statement.

A statement is an operation performed to accomplish a certain task. For example, the following is a line of assignment statement.

var a = 1 + 3;

This statement first uses the var command to declare the variable a, and then assigns the result of the operation of 1 + 3 to the variable a.

1 + 3 is called an expression, which refers to a calculation formula to get the return value. The difference between a statement and an expression is that the former is mainly for performing certain operations and generally does not require a return value; the latter is for obtaining a return value, which must return a value. Expressions can be used wherever values ​​are expected in the JavaScript language. For example, the right side of the equal sign in the assignment statement is expected to be a value, so various expressions can be placed.

The statement ends with a semicolon, and a semicolon means the end of a statement. Multiple statements can be written on one line.

var a = 1 + 3;
var b = "abc";

There can be nothing before the semicolon, and the JavaScript engine treats it as an empty statement.


The above code represents 3 empty statements.

The expression does not need to end with a semicolon. Once you add a semicolon after the expression, the JavaScript engine treats the expression as a statement, which will produce some meaningless statements.

1 + 3;
("abc");

The above two lines of statements simply generate a value and have no practical meaning.

Variable

Concept

Variables are named references to "values". The variable is to name the "value", and then refer to this name, it is equivalent to refer to the value. The name of the variable is the variable name.

var a = 1;

The above code first declares the variable a, and then establishes a reference relationship between the variable a and the value 1, which is called "assigning" the value 1 to the variable a. In the future, quoting the variable name a will get the value 1. The first var is a variable declaration command. It means to notify the interpretation engine that a variable a is to be created.

Note that JavaScript variable names are case sensitive, A and a are two different variables.

Variable declaration and assignment are two separate steps. The above code combines them together. The actual steps are as follows.

var a;
a = 1;

If you just declare a variable without assigning a value, the value of the variable is undefined. undefined is a special value that means "undefined".

var a;
a; // undefined

If you forget to write the var command when assigning a variable, this statement is also valid.

var a = 1;
// Basically equivalent
a = 1;

However, the practice of not writing var is not conducive to expressing intent, and it is easy to create global variables unknowingly, so it is recommended to always use the var command to declare variables.

If a variable is used directly without declaration, JavaScript will report an error, telling you that the variable is undefined.

x;
// ReferenceError: x is not defined

The above code directly uses the variable x, the system will report an error, telling you that the variable x is not declared.

You can declare multiple variables in the same var command.

var a, b;

JavaScript is a dynamically typed language, that is, there are no restrictions on the types of variables, and the types of variables can be changed at any time.

var a = 1;
a = "hello";

In the above code, the variable a was first assigned a value, and then reassigned to a string. In the second assignment, because the variable a already exists, there is no need to use the var command.

If you use var to redeclare an existing variable, it is invalid.

var x = 1;
var x;
x; // 1

In the above code, the variable x is declared twice, and the second declaration is invalid.

However, if a value is assigned during the second declaration, the previous value will be overwritten.

var x = 1;
var x = 2;

// Equivalent to

var x = 1;
var x;
x = 2;

Variable promotion

The way the JavaScript engine works is to parse the code first, get all the declared variables, and then run it line by line. The result of this is that all variable declaration statements will be promoted to the head of the code, which is called variable hoisting.

console.log(a);
var a = 1;

The above code first uses the console.log method to display the value of the variable a on the console. At this time, the variable a has not been declared and assigned, so this is a wrong approach, but in fact no error will be reported. Because of variable promotion, the following code is actually running.

var a;
console.log(a);
a = 1;

The final result is to display undefined, indicating that the variable a has been declared, but has not yet been assigned.

Identifier

Identifier refers to the legal name used to identify various values. The most common identifiers are variable names and function names mentioned later. JavaScript language identifiers are case sensitive, so a and A are two different identifiers.

Identifiers have a set of naming rules, and those that do not conform to the rules are illegal identifiers. When the JavaScript engine encounters an illegal identifier, it will report an error.

Simply put, the identifier naming rules are as follows.

-The first character can be any Unicode letter (including English letters and letters in other languages), as well as dollar signs ($) and underscores (_). -For the second and subsequent characters, in addition to Unicode letters, dollar signs and underscores, numbers 0-9 can also be used.

The following are all legal identifiers.

arg0;
_tmp;
$elem;
π;

The following are illegal identifiers.

1a // The first character cannot be a number
23 // Same as above
*** // Identifier cannot contain asterisks
a+b // Identifier cannot contain a plus sign
-d // Identifiers cannot contain minus signs or conjunction lines

Chinese is a legal identifier and can be used as a variable name.

var temporary variable = 1;

JavaScript has some reserved words that cannot be used as identifiers: arguments, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, false, finally, for , Function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void , While, with, yield.

Comment

The part of the source code that is ignored by the JavaScript engine is called a comment, and its function is to explain the code. JavaScript provides two ways to write comments: one is a single-line comment, starting with //; the other is a multi-line comment, placed between /* and */.

// This is a single line comment

/*
 this is
 Multi-line
 Annotation
*/

In addition, because JavaScript can be compatible with HTML code comments in history, <!-- and --> are also regarded as legal single-line comments.

x = 1; <!-- x = 2;
--> x = 3;

In the above code, only x = 1 will be executed, and the other parts are commented out.

It should be noted that --> will be treated as a single-line comment only at the beginning of the line, otherwise it will be treated as a normal operation.

function countdown(n) {
  while (n-- > 0) console.log(n);
}
countdown(3);
// 2
// 1
// 0

In the above code, n --> 0 will actually be treated as n--> 0, so 2, 1, 0 are output.

Block

JavaScript uses curly braces to group multiple related statements together, called "blocks".

For the var command, JavaScript blocks do not constitute a separate scope.

{
  var a = 1;
}

a; // 1

The above code is inside the block, using the var command to declare and assign the variable a, and then outside the block, the variable a is still valid. The block does not constitute a separate scope for the var command. There is no difference in the use of blocks. In the JavaScript language, it is not common to use blocks alone. Blocks are often used to form other more complex grammatical structures, such as for, if, while, function, etc.

Conditional statements

JavaScript provides if structure and switch structure to complete condition judgment, that is, only when the preset condition is met, the corresponding statement will be executed.

if structure

The if structure first judges the boolean value of an expression, and then executes different statements according to the authenticity of the boolean value. The so-called Boolean value refers to two special values ​​of JavaScript, true means "true" and false means "false".

if (boolean) Statement;

// or
if (Boolean) statement;

The above is the basic form of the if structure. It should be noted that the "Boolean value" is often generated by a conditional expression and must be placed in parentheses to indicate the evaluation of the expression. If the evaluation result of the expression is true, the statement immediately following is executed; if the result is false, the statement immediately following is skipped.

if (m === 3) m = m + 1;

The above code means that only when m is equal to 3, will its value be added by 1.

This writing requires only one statement after the conditional expression. If you want to execute multiple statements, you must add braces after the conditional judgment of if to indicate a code block (multiple statements are combined into one statement).

if (m === 3) {
  m += 1;
}

It is recommended to always use curly braces in the if statement because it is convenient to insert the statement.

Note that in the expressions after if, do not confuse assignment expressions (=), strict equality operators (===) and equality operators (==). In particular, assignment expressions have no comparative effect.

var x = 1;
var y = 2;
if ((x = y)) {
  console.log(x);
}
// "2"

The original intent of the above code is that when x is equal to y, the relevant statement is executed. However, if the strict equality operator is accidentally written as an assignment expression, the result becomes the Boolean value of assigning y to the variable x, and then judging the value of the variable x (equal to 2) (the result is true ).

This kind of error can normally generate a Boolean value, so no error will be reported. In order to avoid this situation, some developers are used to writing constants on the left side of operators. In this case, if the equality operator is accidentally written as an assignment operator, an error will be reported because the constant cannot be assigned.

if (x = 2) {// No error
if (2 = x) {// report an error

As for why the "strict equality operator" (===) is used in preference to the "equal operator" (==), please refer to the "Operators" chapter.

if...else structure

After the if code block, an else code block can also be followed to indicate the code to be executed when the condition is not met.

if (m === 3) {
  // The statement executed when the conditions are met
} else {
  // When the conditions are not met, the statement executed
}

The above code judges whether the variable m is equal to 3, if it is equal, execute the if code block, otherwise execute the else code block.

When multiple judgments are made on the same variable, multiple if...else statements can be written together.

if (m === 0) {
  // ...
} else if (m === 1) {
  // ...
} else if (m === 2) {
  // ...
} else {
  // ...
}

The else code block is always paired with the if statement closest to itself.

var m = 1;
var n = 2;

if (m !== 1)
  if (n === 2) console.log("hello");
  else console.log("world");

The above code will not have any output, and the else code block will not be executed, because it is followed by the nearest if statement, which is equivalent to the following.

if (m !== 1) {
  if (n === 2) {
    console.log("hello");
  } else {
    console.log("world");
  }
}

If you want the else code block to follow the uppermost if statement, you must change the position of the braces.

if (m !== 1) {
  if (n === 2) {
    console.log("hello");
  }
} else {
  console.log("world");
}
// world

switch structure

When multiple if...else are used together, they can be converted to a more convenient switch structure.

switch (fruit) {
  case "banana":
    // ...
    break;
  case "apple":
    // ...
    break;
  default:
  // ...
}

The above code selects and executes the corresponding case according to the value of the variable fruit. If none of the case matches, the final default part is executed. It should be noted that there must be no fewer break statements in each case code block, otherwise the next case code block will be executed instead of jumping out of the switch structure.

var x = 1;

switch (x) {
  case 1:
    console.log("x equals 1");
  case 2:
    console.log("x equals 2");
  default:
    console.log("x is equal to other values");
}
// x is equal to 1
// x is equal to 2
// x is equal to other values

In the above code, there is no break statement in the case code block, which will not jump out of the switch structure, but will continue to execute. The correct way of writing is like the following.

switch (x) {
  case 1:
    console.log("x equals 1");
    break;
  case 2:
    console.log("x equals 2");
    break;
  default:
    console.log("x is equal to other values");
}

Expressions can be used in both the switch statement part and the case statement part.

switch (1 + 3) {
  case 2 + 2:
    f();
    break;
  default:
    neverHappens();
}

The default part of the above code will never be executed.

It should be noted that the expression after the switch statement and the expression after the case statement use the strict equality operator (===) instead of the equality operator ( ==), which means that no type conversion occurs during comparison.

var x = 1;

switch (x) {
  case true:
    console.log("x type conversion occurred");
    break;
  default:
    console.log("x no type conversion occurred");
}
// x is not type converted

In the above code, since the variable x is not type-converted, the case of case true will not be executed. This shows that the "strict equality operator" is used inside the switch statement. For detailed explanation, please refer to the section "Operators".

Ternary operator?:

JavaScript also has a ternary operator (that is, the operator requires three operators) ?:, which can also be used for logical judgment.

(Condition)? Expression 1: Expression 2

In the above code, if the "condition" is true, the value of "expression 1" is returned, otherwise the value of "expression 2" is returned.

var even = n % 2 === 0 ? true : false;

In the above code, if n is divisible by 2, then even is equal to true, otherwise it is equal to false. It is equivalent to the following form.

var even;
if (n % 2 === 0) {
  even = true;
} else {
  even = false;
}

This ternary operator can be regarded as a short form of if...else..., so it can be used in many situations.

var myVar;
console.log(myVar ? "myVar has a value" : "myVar does not have a value");
// myVar does not have a value

The above code uses the ternary operator to output the corresponding prompt.

var msg = "number" + n + "yes" + (n % 2 === 0 ? "even number" : "odd number");

The above code uses the ternary operator to insert different values ​​in the string.

loop statement

The loop statement is used to repeatedly perform an operation, and it has many forms.

while loop

The While statement includes a loop condition and a block of code. As long as the condition is true, the code block will be executed continuously.

while (condition) Statement;

// or
while (condition) statement;

The loop condition of the while statement is an expression and must be placed in parentheses. For the code block, if there is only one statement, the braces can be omitted, otherwise, braces must be added.

while (condition) {
  Statement;
}

The following is an example of the while statement.

var i = 0;

while (i < 100) {
  console.log("i is currently:" + i);
  i = i + 1;
}

The above code will loop 100 times until i equals 100.

The following example is an infinite loop, because the loop condition is always true.

while (true) {
  console.log("Hello, world");
}

for loop

The for statement is another form of the loop command, which can specify the start, end, and termination conditions of the loop. Its format is as follows.

for (initialization expression; condition; increment expression)
  Statement

// or

for (initialization expression; condition; increment expression) {
  Statement
}

Inside the parentheses after the for statement, there are three expressions.

-Initialize expression (initialize): Determine the initial value of the loop variable and execute it only once at the beginning of the loop. -Conditional expression (test): At the beginning of each loop, this conditional expression must be executed, and the loop will continue only if the value is true. -Increment expression (increment): the last operation of each loop, usually used to increment loop variables.

Below is an example.

var x = 3;
for (var i = 0; i < x; i++) {
  console.log(i);
}
// 0
// 1
// 2

In the above code, the initialization expression is var i = 0, that is to initialize a variable i; the test expression is i <x, that is, as long as i is less than x, the loop will be executed; the increment expression The formula is i++, that is, after each cycle ends, i increases by 1.

All for loops can be rewritten as while loops. The above example is changed to a while loop, the code is as follows.

var x = 3;
var i = 0;

while (i < x) {
  console.log(i);
  i++;
}

You can omit any of the three parts (initialize, test, increment) of the for statement, or all of them.

for (;;) {
  console.log("Hello World");
}

The above code omits the three parts of the expression of the for statement, which results in an infinite loop.

do...while loop

The do...while loop is similar to the while loop. The only difference is that the loop body is run once and then the loop conditions are judged.

do Statement;
while (condition);

// or
do {
  Statement;
} while (condition);

Regardless of whether the condition is true or not, the do...while loop runs at least once, which is the biggest feature of this structure. In addition, be careful not to omit the semicolon after the while statement.

Below is an example.

var x = 3;
var i = 0;

do {
  console.log(i);
  i++;
} while (i < x);

break statement and continue statement

Both the break statement and the continue statement have a jump function, which allows the code to be executed out of the existing order.

The break statement is used to jump out of code blocks or loops.

var i = 0;

while (i < 100) {
  console.log("i is currently:" + i);
  i++;
  if (i === 10) break;
}

The above code will only execute the loop 10 times, once i is equal to 10, it will jump out of the loop.

The for loop can also use the break statement to break out of the loop.

for (var i = 0; i < 5; i++) {
  console.log(i);
  if (i === 3) break;
}
// 0
// 1
// 2
// 3

When the above code executes until i is equal to 3, it will jump out of the loop.

The continue statement is used to immediately terminate the current loop, return to the head of the loop structure, and start the next loop.

var i = 0;

while (i < 100) {
  i++;
  if (i % 2 === 0) continue;
  console.log("i is currently:" + i);
}

The above code will output the value of i only when i is an odd number. If i is an even number, it goes directly to the next cycle.

If there are multiple loops, the break statement and continue statement without parameters are only for the innermost loop.

Label

JavaScript language allows, there is a label in front of the statement, which is equivalent to a locator, used to jump to any position in the program. The format of the label is as follows.

label: Statement;

The label can be any identifier, but it cannot be a reserved word, and the sentence part can be any sentence.

Labels are usually used in conjunction with break statements and continue statements to jump out of a specific loop.

top: for (var i = 0; i < 3; i++) {
  for (var j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break top;
    console.log("i=" + i + ", j=" + j);
  }
}
// i=0, j=0
// i=0, j=1
// i=0, j=2
// i=1, j=0

The above code is a double loop block. The top label is added after the break command (note that top does not need to be quoted). When the conditions are met, the double loop will jump out. If no label is used after the break statement, you can only jump out of the inner loop and enter the next outer loop.

Tags can also be used to jump out of code blocks.

foo: {
  console.log(1);
  break foo;
  console.log("This line will not output");
}
console.log(2);
// 1
// 2

When the above code executes to break foo, it will jump out of the block.

The continue statement can also be used with labels.

top: for (var i = 0; i < 3; i++) {
  for (var j = 0; j < 3; j++) {
    if (i === 1 && j === 1) continue top;
    console.log("i=" + i + ", j=" + j);
  }
}
// i=0, j=0
// i=0, j=1
// i=0, j=2
// i=1, j=0
// i=2, j=0
// i=2, j=1
// i=2, j=2

In the above code, there is a label name after the continue command. When the conditions are met, the current loop will be skipped and the next outer loop will be entered directly. If no label is used after the continue statement, you can only enter the next inner loop.

-Axel Rauschmayer, A quick overview of JavaScript