Revisiting JavaScript- Basic syntax trashes
Just began to learn JavaScript for the basic grammar, are skipped when you understand and know about how to use, that is to say, know how to use some normal case, but sometimes meet special writing, will step on some of the pit, again recently in to see the JS, the record this time meet some special pit.
Expressions and statements
On the understanding of statements and expressions, Ruan yifeng wrote in his book:
In general, each line in JS is a statement.
A statement is an operation performed to accomplish something, such as an assignment statement:
var a = 1 + 2;
Copy the code
In this case, the 1+2 above is the expression.
The difference between a statement and an expression is that a statement is intended to perform an operation and generally does not need to return a value, whereas an expression is intended to return a value and must return a value (undefined is not included here).
console.log(3)
Copy the code
This statement is also an expression that prints 3, but the value of this expression is undefined
Spaces and carriage returns
In JavaScript, Spaces and carriage returns have no real meaning most of the time
var a=1
var a = 1
var a = 1
Copy the code
There’s no difference between the three, right
var a
=
1;
console.log(a) // 1
Copy the code
function foo() {
return
1;
}
console.log(foo()) // undefined
Copy the code
You can add a carriage return most of the time, but not after a return, which returns a undefined
If statement
Normal if statement usage is relatively simple
If (1){console.log(1); } if(1) console.log(1)Copy the code
The code above shows that {} can be omitted when there is only one sentence, but this is not recommended
Take a look at the following example
var a = 1
if(a === 2)
console.log(2)
console.log(1)
Copy the code
As in the code above, it prints 1, where {} is omitted after the if, but only one sentence, equivalent to console.log(2) in {}.
A switch statement
var b = 2;
switch (b) {
case 1:
console.log(1);
break;
case 2:
console.log(2);
case 3:
console.log(3);
break;
}
Copy the code
If you look at the example above, you should print 2, but when you run it, you find that 2 and 3 are printed. If you look carefully, there is no break in case 2, so the statement in case 3 will continue to be executed after the execution of case 2.
So most of the time, it’s best not to omit “break” in a case
Logic statements
A & B & C & D first false value or D, is not A true/false | A | B | | C | | D take D, is the first true value or is not A true/falseCopy the code
Logical statements are also easy to step on the pit point, we usually used to do conditional statement judgment, is true when the execution, it can be seen here is actually returned can be judged as true value before the execution of the following conditional statement