This is the 14th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge
A computer program is generally a set of instructions that can be executed by a computer. In programming languages, these instructions are called statements, and JavsScript programs are collections of JavaScript statements. A command issued by a JavaScript statement to the browser to tell it what to do.
JavaScript follows the “statement-expression” structure of common programming languages. In the JavaScript standard, statements are divided into two types: declarations and statements. Let’s take a look at the family of JavaScript statements.
General statement
Conditional statements
If statement
grammar
if(expr)
statement
Copy the code
role
Executes its content statement when the condition is met. This statement can be a block of statements, so that multiple statements can be conditionally executed.
The else structure
The if statement also has an else structure to execute if the condition is not met; A common use is to write if and else as multi-branching conditions, taking advantage of the nesting ability of statements.
A switch statement
The switch statement is inherited from Java. In Java, the switch statement is inherited from C and C++. Originally, the switch statement is a variant of the jump.
-
If you want to use it to branch, you must add break.
** See the following example **
Without a break, it executes everything that satisfies the condition and the rest
The correct approach
Looping statements
The while loop
- Condition is true
- Execute the statement
- Return the condition to continue the judgment
- Until the condition is false, break out of the loop
Here is an example
When 0, the condition is false and the execution is stopped;
The do while loop
-
Execute the statement (at least once)
-
Condition is true
-
J continues executing the statement
-
Return the condition to continue the judgment
-
Until the condition is false, break out of the loop
Here is an example
The condition is that a is less than 10, if not, but still execute once;
The for loop
More concise loop structure.
Syntax format
for (expr1; expr2; expr3) statementCopy the code
other
-
All three expressions in a for statement can be null or include multiple subexpressions separated by commas
-
If expr2 is empty, it will default to true, meaning it will loop indefinitely.
-
In addition to the exPR2 expression ending the loop, you can also use the break statement within the loop statement to end the loop.
for in
The for/in statement is a special form of the for statement
Syntax format
for ( [var/let] variable in <object | array)
statement
Copy the code
- Use var/let to declare variable names directly
- In is followed by object or array
- Assign a value to variable for each value you get as you walk through an object or array.
- Variable is an array index
- 【 object 】 Variable is the name of an object’s property
note
- If an object property is set to a limiting feature such as read-only, archived, or non-enumerable, then it cannot be enumerated using the for/in statement.
Here is an example
Object obj: added an enumerable property c to object obj with enumerable set to false. C: added an enumerable property c to object obj with Enumerable set to false.
- The results of the traversal are not necessarily defined in the order of output, the latest version of the browser is now executed as Chrome, first take out the non-negative integer key, sort the output, and then the rest of the definition of the order of output, [so if the order is required, do not define the keys as pure numbers].
for of
For of is a new loop method in ES6
- Cannot be used directly to traverse objects
- The mechanism behind it is
The iterator mechanism
You can add an iterator to any object so that it can be used in a for of statement
As follows (this example is meaningless)
- You can implement custom rules for traversal of data within an object
let people={
name:'Axjy',
mood:['happy','bad','nice','energetic'],
[Symbol.iterator](){
const _this=this;
let index=0;
return {
next(){
if(index<_this.mood.length){
return {
value:_this.mood[index++],
done:false
}
}else{
return {
value:undefined,
done:true
}
}
}
}
}
};
Copy the code
Symbol.iterator MDN
In practice, we usually don’t need to define iterators this way, we can use generator functions instead
As follows (this example is meaningless)
yield MDN
For await of loop
JavaScript also comes with asynchronous for of for asynchronous generator functions
Here is an example
Define an asynchronous generator function. The asynchronous generator function generates a number every second. This is an infinite generator. This infinite loop code can be used for meaningful operations such as displaying a clock.
function sleep(duration) {
return new Promise(function(resolve, reject) {
setTimeout(resolve,duration);
})
}
async function* foo(){
i = 0;
while(true) {
await sleep(1000);
yield i++;
}
}
for await(let e of foo())
console.log(e);
Copy the code
Exceptions and errors
Try/throw statement
Try /throw statements are used to handle exceptions;
try {
throw new Error("error");
} catch(e) {
console.log(e);
} finally {
console.log("finally");
}
Copy the code
Generally, a throw is used to throw an exception, but from a purely linguistic point of view, we can throw any value, and it doesn’t have to be exception logic, but for the sake of semantic clarity, we don’t recommend using a throw to express any non-exception logic.
- The try statement is used to catch an exception. An exception thrown by a throw can be handled within the structure of the try statement. The try part identifies the code segment in which the exception is caught.
- The catch section is used to do some processing after catching an exception
- The finally section is used to do some cleanup that must be done after execution.
Debug statements
The debugger statement
The debugger statement tells the debugger that there is a breakpoint
Control statement
Break statement
The break statement is used to break out of a loop or switch statement
-
There is a labeled usage that controls which statement structure it is consumed by
The continue statement
The continue statement is used to end the loop and continue
- There is a labeled usage that controls which statement structure it is consumed by
other
block
A statement block is a pair of braces;
Benefits and meaning of statement blocks
- This allows us to treat multiple lines of statements as one line, making if, for, and other statements simple to define.
note
Statement blocks generate scope; An error occurs when you try to access the declaration of the let definition in the block outside of the block.
An empty statement
A null statement is a separate semicolon, which is not really useful.
-
Empty statements exist only for the sake of language design completeness, allowing multiple semicolons to be inserted without throwing an error.
Return statement
The return statement is used in a function. It terminates the function’s execution and specifies the return value of the function
- It can be followed by an expression
Declarative statement
The var statements
The classical way of declaring variables in JavaScript. Now, in the vast majority of cases, let and const are better choices.
-
Declaration must also be initialized;
-
Declare as close as possible to the use location;
-
Don’t mind repeating statements.
Let and const statements
Let and const are declarations of variables. Let and const are declarations of structures such as if and for.
The class declaration
- The most basic use of class requires only the class keyword, the name, and a pair of braces
- Its declaration characteristics are similar to const and let, which are applied to the block-level scope
- The preprocessing phase shields external variables.
class a {
}
Copy the code
Class, you can define a constructor using the constructor keyword. You can also define getters/setters and methods.
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } // Getter get area() { return this.calcArea(); } // Method calcArea() { return this.height * this.width; }}Copy the code
Classes MDN
Function declaration
Ordinary function declaration
function foo(){
}
Copy the code
Async Function declaration
async function foo(){
await sleep(3000);
}
Copy the code
Generator function Declaration
function* foo(){
yield 1;
yield 2;
yield 3;
}
Copy the code
Async Generator function declaration
async function* foo(){
await sleep(3000);
yield 1;
}
Copy the code
conclusion
Note: The above examples are for conceptual purposes only
If there are any mistakes above, please let us know in the comments section!
Click “Like” before you go! 😗