I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, I learned the 3.5 operators in chapter 3 of JavaScirpt Advanced Programming (3rd edition) based on some page searches. So, today is mainly based on the search to carefully study the 3.6 statement in chapter 3, another good day for learning, go, small and !!!!


Today’s Lesson summary

Ecma-262 specifies a set of statements that essentially define the main syntax in ECMAScript, and statements typically use one or more keywords to accomplish a given task.

Statements can be simple, such as telling a function to exit, or complex, such as specifying how many times a command is repeated

  • If statement
  • Do – while statement
  • While statement
  • For statement
  • The for in statement
  • Label statement
  • Break and continue statements
  • With statement
  • A switch statement
  • The debugger statement

If statement

Basic instructions

When the specified condition is true, the if statement executes a statement. If the condition is false, another statement is executed.

function testNum(a) {
  let result;
  if (a > 0) {
    result = 'positive';
  } else {
    result = 'NOT positive';
  }
  return result;
}

console.log(testNum(- 5));
// expected output: "NOT positive"
Copy the code



Grammar specification

if (condition)
   statement1
[else
   statement2]
Copy the code
The statement of specify
condition The value is true or falseexpression
statement1 whenconditionThe statement executed when true. Can be any statement, including deeper internalsifStatements. To execute multiple statements, use theblockStatement ({… }) group these statements; If you do not want to execute the statementemptyStatements.
statement2 ifconditionFalse andelseThe statement executed when a clause exists. Can be any statement, including block statements and nestedifStatements.

Detailed instructions

Multilayer the if… Else statements can use else if clauses. Note: There is no elseif (one word) keyword in Javascript.

if (condition1)
   statement1
else if (condition2)
   statement2
else if (condition3)
   statement3
...
else
   statementN
Copy the code

To see how it works, adjust the nested indentation, okay

if (condition1)
   statement1
else
   if (condition2)
      statement2
   else
      if (condition3)
...
Copy the code

To execute multiple statements in a clause, use statement blocks ({… }). In general, it’s a good habit to use blocks all the time, especially in code that involves nested if statements:

if (condition) {
   statements1
} else {
   statements2
}
Copy the code

Do not confuse true and false of primitive Boolean values with true or false of Boolean objects. Any value that is not undefined, NULL, 0, NaN, or an empty string (“”) is true in conditional statements for any object, even a Boolean object with a false value. Such as:

var b = new Boolean(false);
if (b) // The expression has the value true
Copy the code

Use case

Use the if… else

if (cipher_char === from_char) {
   result = result + to_char;
   x++;
} else {
   result = result + clear_char;
}
Copy the code

Use else if








if (x > 5) {
 /* do the right thing */
} else if (x > 50) {
 /* do the right thing */
} else {
 /* do the right thing */
}
Copy the code

Assignment in conditional expressions

It is not recommended to use assignment solely in conditional expressions, because at first glance the assignment code can easily be mistaken for equivalence comparisons. For example, don’t use the code in the following example:

if (x = y) {
   /* do the right thing */
}
Copy the code

If you need to use an assignment in a conditional expression, wrap the assignment in parentheses. Such as:

if ((x = y)) {
   /* do the right thing */
}
Copy the code

Do – while statement

Basic instructions

do… The while statement creates a loop that executes the specified statement until condition is false. Condition is checked after statement is executed, so the specified statement is executed at least once.


Grammar specification

do
   statement
while (condition);
Copy the code
The statement of specify
statement Execute the statement at least once and at each timeconditionRe-execute if the value is true. To execute a multi-line statement, use theblockStatement ({... }Wrap these statements.
condition An expression evaluated each time in the loop. ifconditionA value of true,statementIt will be executed again. whenconditionIf the value is false, jump todo... whileThe following statement.

Use case

In the following example, do… The while loop iterates at least once and continues until I is no longer less than 5.

HTML content

<div id="example"></div>
Copy the code

JavaScript content

var result = ' ';
var i = 0;
do {
   i += 1;
   result += i + ' ';
} while (i < 5);
document.getElementById('example').innerHTML = result;
Copy the code

The results of



While statement

Basic instructions

A while statement executes a specified piece of code as long as a conditional expression is true, and ends the loop if that expression is not true.

let n = 0;

while (n < 3) {
  n++;
}

console.log(n);
// expected output: 3
Copy the code



Grammar specification

while (condition)
  statement
Copy the code
The statement of specify
condition The conditional expression is evaluated before each loop. If the evaluation is true,statementIt will be executed. If the evaluation is false, it jumps outwhileLoop through the following statements.
statement The statement is executed as long as the conditional expression is evaluated to true. To execute multiple statements in a loop, use block statements ({... }) encapsulates multiple statements. Note: UsebreakStatements inconditionStop the loop until the result is true.

Use case

The following while loop will loop several times until n is equal to 3.

var n = 0;
var x = 0;
while (n < 3) {
  n++;
  x += n;
}
Copy the code

In each cycle, n increases by 1, and then you add n to x. Therefore, at the end of each cycle, the values of x and n are:

  • After the first round:n= 1,x = 1
  • After the second round:n= 2,x = 3
  • After the third round:n= 3,x = 6

When the third loop is completed, the conditional expression n< 3 is no longer true, so the loop terminates.


For statement

Basic instructions

The for statement is used to create a loop that contains three optional expressions surrounded by parentheses, separated by semicolons, followed by a statement (usually a block statement) to execute within the loop.

let str = ' ';

for (let i = 0; i < 9; i++) {
  str = str + i;
}

console.log(str);
// expected output: "012345678"
Copy the code



Grammar specification

for ([initialization]; [condition]; [final-expression])
   statement
Copy the code
The statement of specify
initialization An expression (including an assignment statement) or variable declaration. Typically used to initialize a counter. This expression can be usedvar 或 letKeyword declaration of new variables, usedvarThe declared variable is not local to the loop, but toforLoops are in the same scope. withletDeclared variables are local variables to the statement. The result of this expression is meaningless.
condition A conditional expression is used to determine whether each loop can be executed. If the expression results in true,statementWill be executed. This expression is optional. If ignored, it is considered always true. If the calculated result is false, the execution process is skippedforThe first statement following a statement structure.
final-expression An expression to be executed at the end of each loop. The execution time is next timeconditionBefore calculating. Usually used to update or increment a counter variable.
statement As long asconditionStatement that is executed when the result of true is true. To execute multiple statements inside the loop, use oneBlock statements({... }) to contain the statement to execute. Without any statements to execute, use oneAn empty statement(;).

Use case

Use the for

The following example declares the variable I and assigns it an initial value of 0. The for statement checks if the value of I is less than 9. If it is less than 9, it executes the statement in the block and finally increments the value of I by 1.

for (var i = 0; i < 9; i++) {
   console.log(i);
   // more statements
}
Copy the code

Optional for expression

All three expressions in the parentheses in the for header are optional. For example, the expression in the initialization block is not specified:

var i = 0;
for (; i < 9; i++) {
    console.log(i);
    // more statements
}
Copy the code

Like initialization blocks, conditional blocks are optional. If you omit this expression, you must be sure to jump out of the loop body to avoid creating an infinite loop.

for (var i = 0;; i++) {
   console.log(i);
   if (i > 3) break;
   // more statements
}
Copy the code

You can of course ignore all expressions. Also, be sure to use the break > statement to break out of the loop and also modify (add) a variable so that the condition of the break statement is true at some point.

var i = 0;
for (;;) {
  if (i > 3) break;
  console.log(i);
  i++;
}
Copy the code

Use for without a statement

The following for loop computes the offset position of the node in the final-expression section. It does not need to execute a statement or a set of block statements, so empty statements are used.

function showOffsetPos(sId) {
  var nLeft = 0, nTop = 0;
  for (
    var oItNode = document.getElementById(sId); /* initialization */
    oItNode; /* condition */
    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
  ); /* Semicolon */ 
  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px; \n top: ' + nTop + 'px; ');
}
/* Example call: */
showOffsetPos('content');
// Output:
// "Offset position of "content" element:
// left: 0px;
// top: 153px;"
Copy the code

Tip: Semicolons are mandatory here, one of the few instances in JavaScript where semicolons are mandatory. If there is no semicolon, the line following the loop declaration is treated as a loop statement.


The for in statement

Basic instructions

for… The IN statement iterates through the enumerable properties of an object except Symbol in any order.


Grammar specification

for (variable in object)
  statement
Copy the code
The statement of specify
variable At each iteration, variable is assigned to a different property name.
object An object whose enumerable properties of a non-symbol type are iterated over.

Detailed instructions

for… The IN loop only iterates over enumerable properties (including the enumerable properties on its prototype chain). Objects created using built-in constructors like Array and Object inherit the non-enumerable properties of Object.prototype and String.prototype. For example, the indexOf() method of String or toString() method of Object. The loop iterates through all the enumerable properties of the object itself, as well as properties that the object inherits from its constructor stereotype (more closely approximating the properties of objects in the stereotype chain overwriting stereotype properties).


Delete, add, or modify properties

for… The in loop iterates over the properties of an object in arbitrary order (see the DELETE operator for why you cannot rely on the apparent order of iteration, at least in a cross-browser setup). If a property is modified during an iteration and accessed later, its value in the loop is its value at a later time. A property that was deleted before it was accessed will not be accessed later. Properties that are added to an object during an iteration may be accessed or ignored in subsequent iterations. In general, it is best not to add, modify, or delete properties on an object during iteration, except for properties that are currently being accessed. There is no guarantee that an added attribute will be accessed during the iteration, that a modified attribute (unless it is being accessed) will be accessed before or after the modification, or that a deleted attribute will be accessed before it is deleted.


Array iteration and for… in

** hint: For… In should not be used to iterate over an Array where index order is important. Array indexes are simply enumerated properties with integer names and are the same as generic object properties. There is no guarantee for… In will return indexes in any particular order. for … The IN loop statement returns all enumerable properties, including names of non-integer types and inherited ones. Because the order of iteration is context-dependent, array traversal does not necessarily access elements in order. So when iterating over arrays where order is important, it’s best to use integer indexes for loops (or array.prototype.foreach () or for… Of cycles).


Iterate only over its own properties

If you only want to consider properties of the object itself, rather than its prototype, use getOwnPropertyNames() or hasOwnProperty() to determine if a property is a property of the object itself (propertyIsEnumerable can also be used). Or, if you know there won’t be any interference from outside code, you can extend the built-in prototype with a check method.


Use case

The following function takes an object as an argument. Called to iterate over all the enumerable properties of the passed object and return a string of all the property names and their corresponding values.

var obj = {a:1.b:2.c:3};
Copy the code

for (var prop in obj) { console.log("obj." + prop + "=" + obj[prop]); } // Output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3"


The following function illustrates the use of hasOwnProperty() : Inherited properties are not displayed.

var triangle = {a: 1.b: 2.c: 3};
function ColoredTriangle() {
  this.color = 'red';
}
ColoredTriangle.prototype = triangle;
var obj = new ColoredTriangle();
for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(`obj.${prop} = ${obj[prop]}`); }}// Output:
// "obj.color = red"
Copy the code

Label statement

Basic instructions

Tag statements can be used with break or continue statements. A marker is a statement preceded by an identifier that can be referenced.

let str = ' ';

loop1:
for (let i = 0; i < 5; i++) {
  if (i === 1) {
    continue loop1;
  }
  str = str + i;
}

console.log(str);
// expected output: "0234"

Copy the code

Note: Loops or blocks of statements that use tags are very rare. In general, you can use function calls instead of (token-based) loop jumps.


Grammar specification

label :
   statement
Copy the code
The statement of specify
label Any JavaScript identifier that is not a reserved keyword.
statement JavaScript statements.breakCan be used for any tag statement, whilecontinueCan be used for loop tag statements.

Detailed instructions

You can use a label to uniquely mark a loop, and then use a break or continue statement to indicate whether the program breaks the loop or continues execution. Note that JavaScript does not have a goto statement and the tag can only be used with break or continue. In strict mode, you cannot use “let” as the tag name. It throws a SyntaxError (because let is a reserved identifier).


Use case

Use break in the tag block

You can use tags in blocks of code, but only break statements can use non-cyclic tags.

foo: {
  console.log('face');
  break foo;
  console.log('this will not be executed');
}
console.log('swap');
// this will log:
// "face"
// "swap
Copy the code

Label function declaration

As of ECMAScript 2015, standard function declarations now standardize non-strict code in the Web compatibility attachments of the specification.

L: function F() {}
Copy the code

In strict mode, this throws a SyntaxError:

'use strict';
L: function F() {}
// SyntaxError: functions cannot be labelled
Copy the code

Generator functions cannot be marked whether they are in strict mode or not:

L: function* F() {}
// SyntaxError: generator functions cannot be labelled
Copy the code

Break statement

Basic instructions

The break statement terminates the current loop, switch statement, or label statement, and transfers program control to the statement immediately following the aborted statement.

The break statement contains an optional label that allows the program to get rid of a marked statement. The break statement needs to be embedded in the tag of the reference. The marked statement can be any block statement; It doesn’t have to be a loop.


Grammar specification

break [label];
Copy the code
The statement of specify
label Optional. The identifier associated with the statement label. If the break statement is not in a loop orswitchStatement, the item is required.

Use case

The following function has a break statement that breaks the while loop when I is 3 and returns the value of 3 * x.

function testBreak(x) {
  var i = 0;

  while (i < 6) {
    if (i == 3) {
      break;
    }
    i += 1;
  }

  return i * x;
}
Copy the code

The continue statement

Basic instructions

The continue statement terminates the execution of statements in the current iteration of the current loop or marks the loop and continues the loop at the next iteration.

let text = ' ';

for (let i = 0; i < 10; i++) {
  if (i === 3) {
    continue;
  }
  text = text + i;
}

console.log(text);
// expected output: "012456789"

Copy the code



Grammar specification

continue [ label ];
Copy the code
The statement of specify
label Identifies the statement associated with the label

Detailed instructions

Unlike the break statement, continue does not terminate the iteration of the loop, but rather:

  • In the while loop, the control flow jumps back to the condition judgment;
  • In the for loop, the control flow jumps to the update statement.

The continue statement can contain an optional label to control the program to jump to the next iteration of the specified loop instead of the current one. The continue statement is required to be inside the corresponding loop.


Use case

The following example shows a while loop that executes a continue statement when I is 3. Thus, the values of n are 1, 3, 7, and 12 after several iterations.

i = 0;
n = 0;
while (i < 5) {
   i++;
   if (i === 3) {
      continue;
   }
   n += i;
}
Copy the code

With statement

Basic instructions

The with statement extends the scope chain of a statement.


Grammar specification

with (expression) {
    statement
}
Copy the code
The statement of specify
expression Adds the given expression to the scope chain used when evaluating the statement. Parentheses around expressions are required.
statement Any statement. To execute multiple statements, use oneblockStatement ({… }) group these statements.

Recommend writing

Excessive use of the with statement degrades performance and makes it difficult to debug code. Therefore, it is not recommended to use the with statement when developing large-scale applications. Otherwise, the with statement is regarded as a syntax error


Detailed instructions

JavaScript searches for variables that do not use namespaces through the scope chain, which is associated with the context in which the code is executed or the function that contains the variable. The ‘with’ statement adds an object to the top of the scope chain. If there is an unused variable in the statement with the same name as an attribute in the scope chain, that variable points to that attribute value. If there is no attribute with the same name, a ReferenceError exception is thrown. The use of with is not recommended, as it is prohibited in ECMAScript 5 strict mode. The recommended alternative is to declare a temporary variable to hold the attributes you need.


Performance pros and cons

  • Leon:withStatements can reduce the length of a variable without incurring a performance penalty. It causes little additional computation. Using ‘with’ reduces unnecessary pointer path parsing. Note that in many cases it is possible to achieve the same effect by not using the with statement but using a temporary variable to hold the pointer.
  • Disadvantages:withStatement causes a program to search for a variable value by first looking in the specified object. So variables that aren’t properties of this object are going to be slow to find. If performance is critical, the variables in the statement below ‘with’ should contain only the attributes of the specified object.

The disadvantages of semantic ambiguity

  • Disadvantages:withStatements make code hard to read and make it difficult for the JavaScript compiler to look up a variable on the scope chain and decide which object to value. Look at the following example:
function f(x, o) {
  with (o) 
    print(x);
}
Copy the code

When f is called, x may take a value, or it may take a value from undefined, or if it does, it may take a value from o, or it may take the value of the function’s first argument x (if o does not have this property). If you forget to define x in the object O as the second argument, the program does not report an error; it just takes another value.

  • Disadvantages: ** usewithStatement code that is not forward compatible, especially when using some native data types. Look at the following example:
function f(foo, values) {
    with (foo) {
        console.log(values)
    }
}
Copy the code

If f([1,2,3], obj) is called in the ECMAScript 5 environment, the variable values in the with statement will point to the function’s second parameter values. However, the ECMAScript 6 standard adds a new property to Array.prototype, values, that all Array instances inherit. So in an ECMAScript 6 environment, the variable values in the with statement will point to [1,2,3].values.


Use case

The following with statement specifies the Math object as the default. The variables in the with statement refer to PI, cos, and sin functions of the Math object, respectively, without adding namespaces in front of them.

var a, x, y;
var r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}
Copy the code

A switch statement

Basic instructions

The switch statement evaluates an expression, matches the value of the expression to the case clause, and executes the statement associated with that case.

const expr = 'Papayas';
switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log(`Sorry, we are out of ${expr}. `);
}

Copy the code



Grammar specification

switch (expression) {
  case value1:
    This statement is executed when the result of expression matches value1
    [break; ]case value2:
    This statement is executed when the result of expression matches value2
    [break; ] . case valueN:// Execute this statement when the result of expression matches valueN
    [break; ] [default:
    If expression does not match the value above, execute this statement
    [break; ] ]}Copy the code
The statement of specify
expression An expression used to match a case substatement.
Case valueN optional Used to matchexpression 的 caseClause. ifexpressionWith a givenvalueNMatches, the statement in the case clause is executed untilswitchStatement terminates or encounters onebreak 。
defaultoptional adefaultClause; If given, the clause will be inexpressionThe value ofcaseExecute when none of the statements match.

Detailed instructions

A switch statement first evaluates its expression. It then executes the statement starting with the first case clause until it finds a clause whose expression value is equal to the value of the entered expression (using the strict operator, ===) and transfers control to that clause. (If multiple cases match the supplied value, the first case that matches is selected, even if the cases are not equal to each other.) If no case clause matches, the program looks for the optional default clause and, if it finds one, gives it control and executes the relevant statement. Without the default clause, execution continues until switch ends. By convention, the default clause is the last clause, but you don’t need to do that. The optional break statement ensures that the program immediately jumps out of switch from the relevant case clause and executes the statement following switch. If break is omitted, the program proceeds to the next statement in the switch statement.


Use case

In the following example, if expr is evaluated as” Bananas”, the program will match the case with the value “Bananas” and then execute the statement. When a break is encountered, the program jumps out of the switch and executes the statement behind the switch. If break is omitted, the statement in the case with the value “Cherries” will also be executed.

switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are $0.32 a pound.');
    break;
  case 'Bananas':
    console.log('Bananas are $0.48 a pound.');
    break;
  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '. ');
}

console.log("Is there anything else you'd like?");
Copy the code

The debugger statement

Basic instructions

The debugger statement invokes any available debugging functions, such as setting breakpoints. This statement has no effect if no debugging function is available.


Grammar specification

debugger;
Copy the code

Use case

The following example demonstrates a function that contains a debugger statement. When the function is called, it tries to call an available debugger for debugging.

function potentiallyBuggyCode() {
    debugger;
    // do potentially buggy stuff to examine, step through, etc.
}
Copy the code

Summary of today’s lesson



Today the mood

Today is mainly based on the search to carefully study the 3.5 statement in chapter 3, feel the powerful combination of operators and statements ~~~, feel very good, hope to learn more tomorrow ~~~~


This article is formatted using MDNICE