Recent original articles 😊 :

  • The Great Webpack HMR Study Guide (with Source Analysis)
  • The Great Webpack Build Process Study Guide
  • WeakMap You Don’t Know
  • The Blob you Don’t Know
  • The Awesome Tsconfig. json Guide
  • “200 lines of JS code, with you to implement the code compiler”

preface

Recently interviewed a lot of front end job seekers together with the department boss, among them want to change the learning atmosphere better people account for the majority, but good learning atmosphere also needs a little bit to build out 🌺.

For this reason, we set up our team’s internal “Modern JavaScript Commando”, the first learning content is “Modern JavaScript Tutorial” series, to help team members systematically study and consolidate, and let everyone develop a systematic learning and output learning summary learning way.

This article as the first part of my output learning summary, I hope as a self-test list, help you consolidate knowledge, review the old and new.

Share our study group’s “deposit system” and “deposit record form” here too 🍀

Let’s share the content of the self-test list.

A, Hello World!

1. Script import mode

There are two ways to import JavaScript scripts:

  • <script>Tag insert script;
  • <script>The labelsrcSet the script address.

2. Script tag attributes

The

2.1 the SRC

SRC: specifies the URI of the external script. If SRC is set, the contents of the script tag are ignored.

<script src="example-url.js"></script>
Copy the code

2.2 type

Type: Specifies the language of the referenced script. The property values are MIME types, including TEXT /javascript, TEXT/ECMAScript, Application /javascript, and Application/ECMAScript. If this property is not defined, the script is treated as JavaScript.

ES6 adds the attribute value Module, where code is treated as a JavaScript module.

<script type="text/javascript"></script>
Copy the code

2.3 async

Async specifies that the script is executed asynchronously once it is available. Note: The async property is only applicable to external scripts (only if the SRC property is used). There are several ways to execute an external script: if async=”async” : the script executes asynchronously relative to the rest of the page (the script will be executed while the page continues to parse); If async is not used and defer=”defer” : The script will be executed when the page is finished parsing; If you don’t use async or defer: Read and execute the script immediately before the browser continues parsing the page;

<script async="async"></script>
Copy the code

2.4 the defer

The defer property specifies whether to defer script execution until the page loads.

If your script does not change the contents of the document, add the defer attribute to the

<script defer="defer"></script>
Copy the code

For details, read the MDN

2. Code structure

1. The statement

Statements are syntactic structures and commands that execute actions. Such as: alert (‘ Hello, world! ‘) which can be used to display the message.

2. A semicolon

When there is a line break, the semicolon can be omitted in most cases. But not all of them. For example:

alert(3 +
1
+ 2);
Copy the code

It is advisable for new employees not to omit the semicolon.

3. Comments

Single-line comments begin with two forward slash characters//Start.

// Annotate the text
console.log("leo");
Copy the code

Multiline comments begin with a forward slash and asterisk"/ *"It ends with an asterisk and a diagonal bar"* /".

/* This is a multi-line comment. The second line is comment. * /
console.log("leo");
Copy the code

3. Modern mode, “use strict”

1. The role

JavaScript’s strict mode is a way to use restricted JavaScript, thereby implicitly exiting “sloppy mode.”

The “Use strict” directive converts the browser engine to” modern “mode, changing the behavior of some built-in features.

2. Use

By adding “use strict” to the beginning of the script file/function; To enable strict mode. To enable strict mode globally:

// index.js
"use strict";
const v = "Hi! I'm a strict mode script!";
Copy the code

Turn on strict mode within a function:

// index.js
function strict() {
  'use strict';
  function nested() { 
    return "And so am I!"; 
  }
  return "Hi! I'm a strict mode function! " + nested();
}
Copy the code

3. Pay attention to the point

  1. "use strict"Need to be defined at the very top of the script (except within functions), otherwise strict mode may not be enabled.
  2. Once you’re in Strict mode, you can’t turn it off.

Experience 4.

With “use strict” enabled, assigning to an undefined element throws an exception:

"use strict";
leo = 17; // Uncaught ReferenceError: leo is not defined
Copy the code

When “use strict” is enabled, an exception is thrown when an undeletable attribute is attempted:

"use strict";
delete Object.prototype; // Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
Copy the code

For details, see the MDN Strict Mode section.

Four, variables,

1. Introduction

Variables are “named stores” of data.

2. Use

There are currently three keywords that can be used to define variables: var/let/const. You can read the let and Const commands for the difference.

let name = "leo";
let name = "leo", age, addr;
let name = "leo", age = 27, addr = "fujian";
Copy the code

3. Naming suggestions

There are two restrictions on variable naming:

  1. The variable name must contain onlyLetters, numbers, symbols $_.
  2. The first character must be non-numeric. Here are some suggestions for naming variables:
  • Constants are usually in all caps, as inConst PI = 3.141592
  • Use readable names such asuserNameorshoppingCart.

4. Pay attention to the point

  • JavaScript variable names are case sensitive, such as variablesleoLeoIs different;
  • Non-english letters are allowed for JavaScript variable names, but are not recommended, such asLet safe = "Leo"
  • Avoid the use ofa,b,cThis abbreviation.

5. Data types

JavaScript is a weakly typed or dynamic language. This means that you don’t have to declare the type of the variable in advance; the type is automatically determined during the program’s run. This also means that you can use the same variable to hold different types of data:

var foo = 42;    // foo is a Number now
foo = "bar"; // foo is a String now
foo = true;  // foo is a Boolean now
Copy the code

For more information, read MDN JavaScript Data Types and data structures.

1. Eight data types

The first seven are basic data types, also known as primitive types (the value itself cannot be changed), while object is complex. The eight data types are:

  • numberUsed for any type of number: integer or floating point, integer in the range ±2.
  • bigintUsed for integers of any length.
  • stringFor strings: A string can contain one or more characters, so there is no separate single-character type.
  • booleanUsed fortruefalse.
  • nullFor unknown values — only onenullIndependent type of value.
  • undefinedFor undefined values — only oneundefinedIndependent type of value.
  • symbolUsed as a unique identifier.
  • objectFor more complex data structures.Each type is described in more detail later.

2. Check the data type

Check with the typeof operator:

  • Two forms:typeof xortypeof(x).
  • Returns the type name as a string, for example"string".
  • typeof nullReturns the"object"This is an error in the JavaScript programming language, which is not actually an errorobject.
typeof "leo" // "string"
typeof undefined    // "undefined"
typeof 0     // "number"
typeof NaN   // "number"
typeof 10n   // "bigint"
typeof true  // "boolean"
typeof Symbol("id") // "symbol"
typeof [1.2.3.4]    // "object"
typeof Math  // "object" (1) Math is a built-in object that provides mathematical operations.
typeof null  // "object" (2) An error in the JavaScript language, null is not an object. Null has its own type, which is a special value.
typeof alert // "function" (3) alert is a function in JavaScript.
Copy the code

6. Type conversion

JavaScript variables can be converted to new variables or other data types:

  • By using JavaScript functions
  • Automatic translation through JavaScript itself

1. String conversion

Use the global method String() to convert ** other types of data (any type of number, letter, Boolean, object) ** to String:

String(123);   / / "123"
// The Number method toString()/toExponential()/toFixed()/toPrecision() also has the same effect.
String(false); // "false"
// The Boolean method toString() has the same effect.
String(new Date()); // "Sun Jun 07 2020 21:44:20 GMT+0800"
// The Date method toString() has the same effect.
String(leo);
Copy the code

2. Numerical conversion

There are several ways to convert other types of data to the Number type:

  • Unary operator+
const age = +"22"; / / 22
Copy the code
  • Numbermethods
const age = Number("22"); / / 22
Number.parseFloat("22");  / / 22
Number.parseInt("22");  / / 22
Copy the code
  • Other methods transfer the Number type
/ / a Boolean value
Number(false)     / / returns 0
Number(true)      / / returns 1
/ / date
const date = new Date(a);Number(date);     / / back to 1591537858154
date.getTime();   // Return 1591537858154, the same effect.
// Automatic conversion
5 + null    // Return 5 null converted to 0
"5" + null  // Return "5null";
"5" + 1     // Return "51";
"5" - 1     // Return 4 "5" converted to 5
Copy the code

3. Boolean value conversion

The conversion rules are as follows:

  • Values that are intuitively “empty” (e.g0, empty string,null,undefinedNaN) will befalse.
  • The other values becometrue.
Boolean(1); // true
Boolean(0); // false
Boolean("hello"); // true
Boolean(""); // false
Boolean("0"); // true
Boolean(""); // Blank, also true (any non-empty string is true)
Copy the code

4. Summary

7. Operators

1. Operator concept

Common operators such as addition +, subtraction -, multiplication *, and division /, as an example, introduce some concepts:

let sum = 1 + 2;
let age = +18;
Copy the code

Among them:

  • Add operation1 + 2,12Is 2 operands, the left operand1And the right operator2, i.e.,An operator is the object on which the operator operates.
  • 1 + 2An expression contains two operators, so it is also called the plus sign in the expression+Binary operators.
  • in+ 18The plus sign+Corresponds to only one operator, then it isUnary operator

2. + operator

let msg = "hello " + "leo"; // "hello leo"
let total = 10 + 20;  / / 30
let text1 = "1" + "2"; / / "12"
let text2 = "1" + 2;   / / "12"
let text3 = 1 + "2";   / / "12"
let text4 = 1 + 2 + "3";  / / "33"
let num = +text1; // 12 To the Number type
Copy the code

Operator precedence

Operator precedence determines the order in which operations are executed in an expression, with higher precedence operators being executed first. The following table ranks all operators in order of priority from highest (20) to lowest (1).

priority Operation type Correlation between The operator
20 parentheses N/A (irrelevant) (...).
19 Member access From left to right ... ....
Member access to be counted From left to right ... [...].
new(with parameter list) n/a The new... (...).
A function call From left to right ... (...).
Optional chaining From left to right ? .
18 new(No parameter list) From right to left The new...
17 Increasing the rear(Operator after) n/a
... ++
The rear of diminishing(Operator after) ... --
16 Logic is not From right to left ! ...
According to a non ~...
One yuan addition +...
One yuan subtraction -...
Increasing pre – + +...
Front of diminishing -...
typeof Typeof...
void Void...
delete The delete...
await Await...
15 power From right to left ... * *...
14 The multiplication From left to right
... *...
division ... /...
modulus ... %...
13 add From left to right
... +...
subtraction ... -...
12 According to a shift to the left From left to right ... < <...
According to the position moves to the right ... > >...
Unsigned right shift ... > > >...
11 Less than From left to right ... <...
Less than or equal to ... < =...
Is greater than ... >...
Greater than or equal to ... > =...
in ... The in...
instanceof ... Instanceof...
10 The equal sign From left to right
... = =...
The equal sign ... ! =...
All the equals sign ... = = =...
Not all equal ... ! = =...
9 Bitwise and From left to right ... &...
8 The bitwise exclusive or From left to right ... ^...
7 Bitwise or From left to right ... |...
6 Logic and From left to right ... &&...
5 Logic or From left to right ... | |...
4 Conditional operator From right to left ... ? ... :...
3 The assignment From right to left ... =...
... + =...
... - =...
... * =...
... / =...
... % =...
... < < =...
... > > =...
... > > > =...
... & =...
... ^ =...
... | =...
2 yield From right to left Yield...
yield* Yield *...
1 Expansion operator n/a .
0 The comma From left to right ... ,...
3 > 2 && 2 > 1
// return true
3 > 2 > 1
// Return false because 3 > 2 is true and true > 1 is false
// add parentheses to clarify :(3 > 2) > 1
Copy the code

Comparison of values

1. Common comparisons

The comparison of values in JS is very mathematical:

  • Greater than/less than/greater than or equal to/less than or equal to:a>b / a<b / a>=b / a<=b
  • To judge equality:
// Use ==, not strictly equal, does not care about the value type
// The == operator implicitly casts the operands of the comparison and then compares them
'1'= =1; // true
// Use ===, strict equality, care about the value type
// Treat numeric values -0 and +0 as equal, and consider number. NaN not equal to NaN.
'1'= = =1; // false
Copy the code

Equality Judgment in MDN JavaScript

  • 3. Like equality of judgment, there are two kinds:! = / ! = =

(object.is ())

ES6 adds the object. is method to determine whether two values are the same. The syntax is as follows:

Object.is(value1, value2);
Copy the code

The two values are the same if either of the following is true:

  • Both values are undefined
  • Both values are null
  • Both values aretrueOr arefalse
  • Two values are strings of the same number of characters in the same order
  • Both values point to the same object
  • Both values are numbers and
    • Is is zero+ 0
    • Is zero0
    • Is NaN
    • Examples of the same number except for zero and NaN:
Object.is('foo'.'foo');     // true
Object.is(window.window);   // true
Object.is('foo'.'bar');     // false
Object.is([], []);           // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo);         // true
Object.is(foo, bar);         // false
Object.is(null.null);       // true
/ / special case
Object.is(0.0);            // false
Object.is(0, +0);            // true
Object.is(0.0);           // true
Object.is(NaN.0/0);         // true
Copy the code

Compatibility with Polyfill processing:

if (!Object.is) {
  Object.is = function(x, y) {
    // SameValue algorithm
    if (x === y) { // Steps 1-5, 7-10
      // Steps 6.b-6.e: +0 != -0
      returnx ! = =0 || 1 / x === 1 / y;
    } else {
      // Step 6.a: NaN == NaN
      returnx ! == x && y ! == y; }}; }Copy the code

3. Compare null and undefined

For equality, the judgment is simple:

null= =undefined;  // true
null= = =undefined; // false
Copy the code

For other comparisons they first convert the bit number: NULL to 0 and un______ to NaN.

null > 0;  // false 1
null> =0; // true 2
null= =0; // false 3
null < 1;  // true 4
Copy the code

Null == 0; False == == == == == == == == =

undefined > 0;  // false 1
undefined > 1;  // false 2
undefined= =0; // false 3
Copy the code

Lines 1 and 2 both return false because undefined is converted to NaN in the comparison, and NaN is a special numeric value that will return false when compared with any value. Line 3 returns false because it is an equality check, and undefined is only equal to null and not to any other value.

Alert/prompt/confirm

1. alert

Displays a warning dialog box with the specified text content and an OK button. Note: The modal box pops up and the script is paused until the user clicks the OK button.

/ / grammar
window.alert(message);
alert(message);
/ / sample
alert('hello leo! ');
Copy the code

Message is a string of text to be displayed in the dialog box and is converted to a string if any other type of value is passed in.

2. prompt

Displays a dialog box containing a text message that prompts the user to enter text. Note: The modal box pops up and the script is paused until the user clicks the OK button. When clicking OK returns the text, clicking Cancel or pressing Esc returns null. The syntax is as follows:

let result = window.prompt(text, value);
Copy the code
  • resultA string used to store user input text, or null.
  • textA string used to prompt the user for input. This parameter can be omitted if there is no prompt.
  • valueThe default value in the text input box. This parameter can also be omitted. However, in Internet Explorer 7 and 8, omitting this parameter causes the input box to display the default value “undefined”.

3. confirm

The window.confirm () method displays a modal dialog box with an optional message and two buttons (OK and cancel). Note: The modal box pops up and the script is paused until the user clicks the OK button. The syntax is as follows:

let result = window.confirm(message);
Copy the code
  • Message is an optional string to display in the dialog box.
  • Result is a Boolean value indicating whether to select OK or cancel (true for OK).

10. Conditional operators: if and ‘? ‘

1. If statements

When the if statement is a conditional expression, it converts the expression to a Boolean value. When it is a Truthy, it executes the code inside. The conversion rules are as follows:

  • digital0, empty string"",null,undefinedNaNWill be converted tofalse. Because they’re called “falsy” values.
  • Other values are converted totrue“, so they are called “truthy”.

Ternary operators

The conditional (ternary) operator is the only JavaScript operator that uses three operands. A condition is followed by a question mark (?). If the condition is Truthy, the expression A after the question mark is executed; The expression A is followed by A colon (:), and if the condition is falsy, the expression B following the colon will be executed. This operator is often as [if] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if… Else) statement. Grammar:

condition ? exprIfTrue : exprIfFalse
Copy the code
  • The result of the condition evaluation is used as an expression for a condition.
  • ExprIfTrue The expression exprIfTrue will be evaluated if the expression condition evaluates to Truthy (which is equal to true or can be converted to true).
  • ExprIfFalse If the expression condition evaluates to falsy (which can be converted to false), the expression exprIfFalse will be executed. Example:
let getUser = function(name){
	return name === 'leo' ? 'hello leo! ' : 'unknow user';
}
// This can be abbreviated as:
let getUser = name= > name === 'leo' ? 'hello leo! ' : 'unknow user';
getUser('leo'); // "hello leo!"
getUser('pingan'); // "unknow user"
Copy the code

11. Logical operators

Detailed can read “MDN logical operators”.

1. Introduction to operators

The logical operators are shown in the following table (where _expr_ can be of any type, not necessarily a Boolean):

The operator grammar instructions
Logic AND, AND (&&) _expr1_ && _expr2_ ifexpr**1**Can be converted totrue, the returnexpr**2**; Otherwise, returnexpr**1**.
Logic OR, OR (||) _expr1_ || _expr2_ ifexpr**1**Can be converted totrue, the returnexpr**1**; Otherwise, returnexpr**2**.
Logical NOT, NOT (!) ! _expr_ ifexprCan be converted totrue, the returnfalse; Otherwise, returntrue.

If a value can be converted to true, it is called truthy, and if it can be converted to false, it is called falsy. Expressions that will be converted to false include:

  • null;
  • NaN;
  • 0;
  • Empty string ("" or ' 'The or ` ` ` `);
  • undefined. although&&||Operators can use non-boolean operands, but they can still be considered Boolean operators because their return value can always be converted to a Boolean value. If you want to explicitly convert their return value (or expression) to a Boolean value, useDouble non operator(i.e.!!!!!) orBooleanConstructor. There are three logical operators in JavaScript:||(or),&&(with),!(a).

2. Operator example

  • Logic and (&&) returns true if all conditions are true, otherwise false.
a1 = true  && true      // t &&t returns true
a2 = true  && false     // t && f returns false
a3 = false && true      // f &&t returns false
a4 = false && (3= =4)  // f && f returns false
a5 = "Cat" && "Dog"     // t &&t returns "Dog"
a6 = false && "Cat"     // f &&t returns false
a7 = "Cat" && false     // t && f returns false
a8 = ' '    && false     // f &&f returns ""
a9 = false && ' '        // f && f returns false
Copy the code
  • Logic or (| |) all conditions there have been a true returns true, false otherwise.
o1 = true  || true      / / t | | t return true
o2 = false || true      / / f | | t return true
o3 = true  || false     / / t | | f returns true
o4 = false| | -3= =4)  / / f | | f returns false
o5 = "Cat" || "Dog"     / / t | | t return to the "Cat"
o6 = false || "Cat"     / / f | | t return to the "Cat"
o7 = "Cat" || false     / / t | | f to return to the "Cat"
o8 = ' '    || false     / / f | | f returns false
o9 = false || ' '        / / f | | f return ""
Copy the code
  • Logic is not (!)
n1 = !true              / /! T returns false
n2 = !false             / /! Returns true f
n3 = !' '                / /! Returns true f
n4 = !'Cat'             / /! T returns false
Copy the code
  • Double bad luck (!!)
n1 = !!true                   / /!!!!! Truthy returns truen2 = !! {}/ /!!!!! Truthy returns true: any object is truthy...n3 = !! (new Boolean(false))   / /... Even Boolean objects whose.valueof () returns false!
n4 = !!false                  / /!!!!! Falsy returns false
n5 = !!""                     / /!!!!! Falsy returns false
n6 = !!Boolean(false)         / /!!!!! Falsy returns false
Copy the code

3. Boolean conversion rules

  • Converts && | |
condi1 && confi2
/ / convert! (! condi1 || ! condi2)Copy the code
  • Converting the | | &&
condi1 || condi2
/ / convert! (! condi1 && ! condi2)Copy the code

4. Short circuit value

Since logical expressions operate from left to right, they can also be “short-circuited” using the following rules:

  • (some falsy expression) && (_expr)_The result of short circuit calculation is false.
  • (some truthy expression) || _(expr)_The short-circuit calculation is true. Short circuit means the EXPR part of the above expressionWill not be executed, so any side effects of EXPr will not take effect (for example, if expr is a function call, the call will not occur). The reason for this is that the value of the entire expression is determined after the first operand has been evaluated. Here’s an example:
function A(){ console.log('called A'); return false; }
function B(){ console.log('called B'); return true; }
console.log( A() && B() );
// logs "called A" due to the function call,
// then logs false (which is the resulting value of the operator)
console.log( B() || A() );
// logs "called B" due to the function call,
// then logs true (which is the resulting value of the operator)
Copy the code

5. Pay attention to

With operation & priority than or operation | |. So the code a & b | | c & d completely like && expression with parentheses: (a & b) | | (c & d).

Loop: while and for

1. The while loop

Read MDN While for more details. A while statement can execute a specified piece of code if a conditional expression is true, ending the loop when that expression is not true. Such as:

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

When the body of a loop is a single line, you can do without braces:

let i = 3;
while(i) console.log(i --);
Copy the code

2. do… The while loop

Read MDN Do… While for more details. do… The while statement creates a loop that executes the specified statement until the condition value is false. The condition is checked after the statement is executed, so the specified statement is executed at least once. Such as:

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

3. The for loop

Read MDN for for details. The for statement is used to create a loop and contains three optional expressions that are enclosed in parentheses, separated by semicolons, followed by a statement (usually a block statement) for execution within the loop. Grammar, such as:

for (begin; condition; step) {
  / /... The loop body...
}
Copy the code

Example:

for (let i = 0; i < 3; i++) {
  console.log(i);
}
Copy the code

Description:

begin i = 0 This is executed once upon entering the loop.
condition i < 3 Check before each iteration of the loop. If false, stop the loop.
The body of the loop alert(i) If the condition is true, run repeatedly.
step i++ Executes after each iteration of the body of the loop.

4. Optional for expressions

All three expressions in the header parentheses of the for statement are optional.

  • Do not specify an initialization block in an expression
var i = 0;
for (; i < 3; i++) {
    console.log(i);
}
Copy the code
  • Do not specify a conditional block in an expression, which requires the loop to end in the body of the loop, otherwise an infinite loop occurs
for (var i = 0;; i++) {
   console.log(i);
   if (i > 3) break;
}
Copy the code
  • Without specifying all of the expressions, you also need to specify the condition for ending the loop in the body of the loop
var i = 0;
for (;;) {
  if (i > 3) break;
  console.log(i);
  i++;
}
Copy the code

5. Break statement

Read MDN Break for details. The break statement terminates the current loop, switch statement, or label statement, and flows program control to the statement immediately following the aborted statement. In the while statement:

function testBreak(x) {
  var i = 0;
  while (i < 6) {
    if (i == 3) {
      break;
    }
    i += 1;
  }
  return i * x;
}
Copy the code

Alternatively, you can tag blocks of code and specify the label of the block statement to skip in the break:

outer_block:{
  inner_block: {console.log ('1');
    break outer_block;      // breaks out of both inner_block and outer_block
    console.log (': - (');    // skipped
  }
  console.log ('2');        // skipped
}
Copy the code

Note that the break statement must be embedded in the tag or code block to which it is applied, otherwise an error will be reported:

block_1:{
  console.log ('1');
  break block_2;            // SyntaxError: label not found
}
block_2:{
  console.log ('2');
}
Copy the code

6. The continue statement

The continue declaration terminates statement execution in the current iteration of the current or marked loop and continues the loop on the next iteration. Unlike the break statement, a continue does not terminate the iteration of the loop, but rather:

  • In the while loop, the control flow jumps back to the condition;
  • In the for loop, the control flow jumps to the update statement. Note: Continue must also be inside the corresponding loop, otherwise an error will be reported.
i = 0;
n = 0;
while (i < 5) {
   i++;
   if (i === 3) {
      continue;
   }
   n += i;
}
Copy the code

With the label:

var i = 0, 
    j = 8;
checkiandj: while (i < 4) {
   console.log("i: " + i);
   i += 1;
   checkj: while (j > 4) {
      console.log("j: "+ j);
      j -= 1;
      if ((j % 2) = =0)
         continue checkj;
      console.log(j + " is odd.");
   }
   console.log("i = " + i);
   console.log("j = " + j);
}
Copy the code

7. Pay attention to

banbreak/continueIn the ‘? ‘on the right:

(i > 5)?console.log(i) : continue; // Continue is not allowed in this position
Copy the code

This will prompt a syntax error. Note that non-expression syntactic structures cannot be associated with ternary operators? Use them together. In particular, instructions such as break/continue do not allow this.

8. To summarize

Three cycles:

  • whileCheck the conditions before each iteration.
  • do.. whileCheck the condition after each iteration.
  • for (;;)Conditions are checked before each iteration, and other Settings can be used. Usually usewhile(true)To construct an “infinite” loop. This loop, like any other loop, can be passedbreakInstruction to terminate. If we don’t want to do anything in the current iteration and want to move on to the next iteration, we can usecontinueThe instructions.break/continueSupport for labels before loops. The label isbreak/continueThe only way to break out of a nested loop to go outside.

13. “switch” statement

The switch statement is used to match the value of an expression to a case statement and execute the statement corresponding to the case. The switch statement can replace multiple if statements, providing a more descriptive way for multiple branch choices.

1. Grammar

The switch statement contains at least one case block and an optional default block:

switch(expression) {
  case 'value1':
    // do something ...
    [break]
   
  default:
    // ...
    [break]}Copy the code

When the value of expression matches value1, the code block in the expression is executed. If there is no case clause, the default clause is selected for execution. If there is no default clause, the execution ends with the switch.

2. Use case groups

By case grouping, we mean sharing the same piece of code with multiple case branches, such as case 1 and Case 2 in the following example:

let a = 2;
switch (a) {
  case 1: // (*) The following two cases are grouped together
  case 2:
    console.log('case is 1 or 2! ');
    break;
  case 3:
    console.log('case is 3! ');
    break;
  default:
    console.log('The result is default.');
}
// 'case is 1 or 2! '
Copy the code

3. Pay attention to the point

  1. expressionThe value of the expression is equal tocaseThe comparison of values is strictly equal:
function f(n){
    let a ;
    switch(n){
        case 1:
            a = 'number';
            break;
        case '1':
            a = 'string';
            break;
        default:
            a = 'default';
            break;
    }
    console.log(a)
}
f(1);   // number
f('1'); // string
Copy the code
  1. ** If notbreak, the program will proceed to the next ** without any checks**case** :
let a = 2 + 2;
switch (a) {
	case 3:
    console.log( 'Too small' );
  case 4:
    console.log( 'Exactly! ' );
  case 5:
    console.log( 'Too big' );
  default:
    console.log( "I don't know such values" );
}
// Exactly!
// Too big
// I don't know such values
Copy the code
  1. **default** **放在 ****case** Above does not affect matching:
function f(n){
  switch (n) {
    case 2:
      console.log(2);
      break;
    default:
      console.log('default')
      break;
    case 1:  
      console.log('1');
      break;
  }
}
f(1); / / 1
f(2); / / 2
f(3); // default
Copy the code
  • switchExists in statementlet / constRepeat statement questions:
// The following definitions will report an error
function f(n){
    switch(n){
        case 1:
            let msg = 'hello';
            console.log(1);
            break;
        case 2: 
            let msg = 'leo';
            break;
        default: 
            console.log('default');
            break; }}// Error: Uncaught SyntaxError: Identifier 'msg' has already been declared
Copy the code

This is because the two lets are in the same block-level scope, so they are considered duplicate declarations of the same variable name. To resolve this, wrap the case statement in parentheses:

function f(n){
    switch(n){
        case 1: {// added brackets
            let msg = 'hello';
            console.log(msg);
            break;
        }
        case 2: {
            let msg = 'leo';
            console.log(msg);
            break;
        }
        default: 
            console.log('default');
            break; }}Copy the code

Xiv. Functions

Functions allow a piece of code to be called multiple times, avoiding duplication of code. Some built-in functions, such as alert(MSG)/Prompt (MSG, default)/confirm(quesyion), etc.

1. Function definition

There are two ways to define a function: a function declaration and a function expression.

1.1 Function Declaration

Let’s define a simple getUser function:

function getUser(name){ return 'hello ' + name; } getUser('leo"); // Call the functionCopy the code

To define a function through a function declaration, it consists of the following parts:

  • Function name –getUser
  • Function argument list –name
  • Function’s JS execution statement –return 'hello ' + name

1.2 Function Expression

Like declaring a variable, let’s use getUser again:

let getUser = function(name){
	return 'hello ' + name;
}
Copy the code

In addition, a function expression can also provide a function name and be used within a function to refer to the function itself:

let fun = function f(n){
    return n < 3 ? 1 : n * f(n - 1);
}
fun(3);  / / 3
fun(5);  / / 60
Copy the code

2. Function calls

When a function is defined, it is not automatically executed. Instead, it needs to be called using the function name, as in the example above:

fun(3);  / / 3
Copy the code

Just note: When defining a function using a function expression, the method that calls the function must be written after the definition, otherwise an error will be reported:

console.log(fun());  // Uncaught ReferenceError: fun is not defined
let fun = function(){return 1};
Copy the code

This problem does not occur with function declarations:

console.log(fun());  / / 1
function fun(){return 1};
Copy the code

The reason is that function promotion applies only to function declarations, not to function expressions.

3. Variables in the function

Within a function, you can use both local and external variables.

3.1 Local Variables

Variables declared in a function are visible only within that function.

let fun = function(){
	let name = 'leo';
}
fun();
console.log(name); // Uncaught ReferenceError: name is not defined
Copy the code

3.2 Global Variables

You can use external variables within a function and modify their values.

let name = 'leo';
let fun = function(){
	let text = 'Hello, ' + name;
  console.log(text);
}
fun(); // Hello, leo
Copy the code

When the function also has a variable with the same name as the external variable, the external variable is ignored:

let name = 'leo';
let fun = function(){
  let name = 'pingan8787';
	let text = 'Hello, ' + name;
  console.log(text);
}
fun(); // Hello, pingan8787
Copy the code

4. Function parameters

Starting with ECMAScript 6, there are two new types of arguments: default arguments and remaining arguments.

4.1 Default Parameters

If no argument is passed to the function, the argument defaults to undefined. The usual way to set the parameter default is to do this:

// Default values were not set before ES6
function f(a, b){
    b = b ? b : 1;
    return a * b;
}
f(2.3);  / / 6
f(2);    / / 2
// ES6, set the default value
function f(a, b = 1){
    return a * b;
}
f(2.3);  / / 6
f(2);    / / 2
Copy the code

4.2 Remaining Parameters

An indefinite number of parameters can be represented as an array, as follows:

function f (a, ... b){
    console.log(a, b);
}
f(1.2.3.4); // a => 1 b => [2, 3, 4]
Copy the code

When it comes to arguments, you can’t leave out the arguments object.

4.3 the arguments object

The actual arguments to the function are stored in an array-like arguments object. Inside the function, we can use the arguments object to get all the arguments to the function:

let fun = function(){
    console.log(arguments);
    console.log(arguments.length);
}
fun('leo'); 
// Arguments [" Leo ", callee: ƒ, Symbol(symbol.iterator): ƒ]
/ / 1
Copy the code

Here’s a practical example of a function that concatenates any number of arguments into a string and outputs it:

let argumentConcat = function(separator){
	let result = ' ', i;
  for(i = 1; i < arguments.length; i ++){
  	result += arguments[i] + separator;
  }
  return result;
}
argumentConcat(', '.'leo'.'pingan'); //"leo,pingan,"
Copy the code

5. Function return value

At any point in the function, specify the return instruction to stop the function’s execution and return the value specified by the function.

let sum = function(a, b){
	return a + b;
};
let res = sum(1.2);
console.log(res); / / 3
Copy the code

By default, a null return or function without a return returns undefined.

Function expression

A function expression is a method of defining functions. This section focuses on the difference between a function expression and a function declaration:

1. Grammar differences

// Function expression
let fun = function(){};
// Declare the function
function fun(){}
Copy the code

2. Create timing differences

Function expressions are created when code execution arrives, and are available only from that moment. A function can be called before its declaration is defined.

// Function expression
fun();  // Uncaught ReferenceError: fun is not defined
let fun = function(){console.log('leo')};
// Declare the function
fun();  // "leo"
function fun(){console.log('leo')};
Copy the code

3. Usage suggestions

It is recommended to give priority to the function declaration syntax, which provides more flexibility in organizing code because we can call the function before declaring it.

16. Arrow function

This section briefly introduces the basics of arrow functions, which will be covered in the following sections. Function arrow expressions are new syntax for function expressions in ES6, also called fat arrow functions, variations: more concise functions and this.

1. More concise code

// There is one parameter
let f = v= > v;
/ / is equivalent to
let f = function (v){return v};
// There are multiple arguments
let f = (v, i) = > {return v + i};
/ / is equivalent to
let f = function (v, i){return v + i};
/ / no parameters
let f = (a)= > 1;
/ / is equivalent to
let f = function (){return 1};
let arr = [1.2.3.4];
arr.map(ele= > ele + 1);  // [2, 3, 4, 5]
Copy the code

2. Pay attention to the point

  1. The arrow function does not existthis;
  2. The arrow function cannot be treated asThe constructorThat is, it cannot be usednewInstantiation;
  3. The arrow function does not existargumentsObject, that is, not available, but availablerestParameter substitution;
  4. The arrow function cannot be usedyieldCommand, which cannot be used as a Generator function. A simple example:
function Person(){
  this.age = 0;
  setInterval((a)= > {
    this.age++;
  }, 1000);
}
var p = new Person(); // The timer is executing all the time
Copy the code

conclusion

This article, as the first part of the “Preliminary and Intermediate front-end JavaScript Self-test List”, introduces the content of common basic knowledge, and in the learning materials, the knowledge combined with the actual development of the scene is introduced. Hope to help you to test their own JavaScript level and check the gaps, the old know new.

Author Ping-an wang
E-mail [email protected]
Blog posts www.pingan8787.com
WeChat pingan8787
Recommended Articles of the Day Github.com/pingan8787/…
ES small volumes js.pingan8787.com
Finch Knowledge Base Cute-FrontEnd