JS syntax and variables

1. Learning JavaScript for the first time

The front three layers

language function
The structure layer HTML Build the structure, place the parts, describe the semantics
Style, CSS Beautify the page and realize the layout
Behavior layer JavaScript Achieve interactive effects, data transceiver, form verification, etc

NodeJS extends JavaScript’s reach to the server side.

ECMAScript is the JavaScript standard:

JavaScript implements ECMAScript; ECMAScript regulates JavaScript.

The JavaScript system is divided into three parts :(1) the language core is divided into ECMAScript5 and ECMAScript6,7,8,9; (2) DOM; (3) BOM.

JavaScript syntax and variables

Where JavaScript is written:

1. Write JavaScript code inside the

2. Save the code as a separate.js file and import it in an HTML file;

Note: JavaScript does not run in isolation from HTML web pages (NodeJS will, of course, be a standalone platform for JavaScript).

3. Output statements

1. Alert () statement – An alert box is displayed;

2. Console.log () statement – console output.

Recognition output statement

1.alert(‘ MOOCs ‘);

Alert: Alert () is a built-in function that encapsulates a function and calls it with parentheses.

The word ‘MOOC’ is an argument to the function, and since it’s a string, we need to enclose it in quotes.

A semicolon should be written at the end of the statement. Please note that the input method is English.

2. Console. log(‘ MOOC ‘);

Console is a built-in JS object that calls its built-in log “methods” by “clicking”. Methods are the functions that an object can call.

4. Learn how to handle errors

1. Accidentally wrote a Chinese semicolon at the end;

uncaught SyntaxError: Invalid or unexpected token

Uncaught syntax errors: invalid or incorrect symbols.

Note: Wrong line number (1 line error possible).

2. Forget to enclose the content in quotation marks.

Uncaught ReferenceError: MOOC is not defined

Uncaught reference error: MOOCs are not defined.

3. Incorrect spelling alert;

Uncaught ReferenceError: Alret is not defined;

Uncaught reference error: ALret is not defined.

REPL environment: The console is also a REPL environment that can be used to temporarily test the value of an expression.

5, variables,

What variables are: Variables are symbols that store values in memory; Variables are not numbers themselves; they are simply containers for storing numbers.

Define a variable: To use a variable, the first step is to declare it and assign it a value.

var a =5;

Use the var keyword to define variables; The equal sign indicates assignment.

Use of variables: When a variable is assigned a value, it can be used. Do not use quotation marks when using variables.

console.log( a);

Default values for variables:

The default value of a variable is undefined, but no initial value is assigned.

A variable is not officially initialized until it has been defined by var and assigned an initial value.

var a = 10;
console.log(a);// undefined

a=10;

console.log(a) ;/ / 10
Copy the code

Common errors with variables:

1. Assigning a value to var instead of the var definition will not raise an error, but will cause scope problems. You must write var when defining variables.

2. Attempting to use a character that is neither defined nor assigned by var will result in a reference error. Variables must be assigned before being used

Naming conventions for identifiers (variables, functions, class names, object attributes, etc.) :

1. The name can contain only letters, digits, underscores (_), and underscores ($), but cannot start with a digit.

2. The value cannot be a keyword or reserved word.

3. Case sensitive,a and A are two different variables.

Good variable naming: Hump naming :mathTestScore.

Variable declaration:

Declare and initialize both variables with a comma;

var a =0 , b =0 ;

Variable declaration enhancement:

Improved variable declarations: You can use a variable declared later in advance without throwing an exception.

When a variable declaration is promoted, only the definition of the variable is promoted, not its value.

Matters needing attention:

The enhancement of variable declarations is a feature of JavaScript, so it often comes up with questions.

In actual development, it is important to define and assign initial values to variables before using them.

6. Key points

1. What are the main layers of front-end development? What are the languages and functions?

2. Where is JavaScript written?

3. What output statements does JavaScript have?

4. How to define variables? What are the legal naming conventions for variables?

7. Difficult content

1. Var defines a variable, but does not assign an initial value.

2. What is the promotion of variable declarations?

3. What is the function of the equal sign in JavaScript?

JS basic data types

1. Introduction and detection of data types

There are two main types of data in JavaScript:

1. Basic data types: Number, String, Boolean, Undefined, and Null

2. Complex data types: Object, Array, Function, RegExp, Date, Map, Set, Symbol, etc.

Typeof operators: use the typeof operator to detect the typeof a value or variable.

Note: Typeof is not a function, but an operator; I don’t need parentheses.

Typeof detection results of five basic data types:

Type name Typeof detection results Value for
Numeric types number 5
String type string Mooc Network
Boolean type boolean True, false,
Undefined type undefined undefined
Null type The object (remember) null

2, Number type

All numbers are numeric types regardless of size, size, or number.

The 0 can be omitted from the decimal. A decimal between 0 and 1 May be written without a 0. . 5; / / 0.5 typeof. 5; //number

Scientific notation: Larger or smaller numbers (with smaller absolute values) can be written as scientific notation.

3e8; / / 300000000

typeof 3e8; //number

A special numeric NaN:

NaN is English for “not a number,” that is, “not a number,” but it is a numeric value.

typeof NaN; //number

Zero divided by zero is NaN, and in fact, in mathematics, if you don’t get a number, you get NaN.

NaN has a “strange” quality: it is not self-equal. This knowledge point will be covered in subsequent lectures.

3. The String type

Strings are “the natural language of mankind”. The string must be enclosed in quotation marks, either double or single.

Distinguish numbers from strings: The number 11 is semantically different from the string ’11’, which represents a number and is text.

typeof 11; // number

typeof ’11’; //string

String concatenation: The plus sign can be used to concatenate multiple strings.

‘imo’ + ‘oc ‘; //’immoc’

Concatenation of strings and variables: To “insert” the value of a variable into a string, “break the link.”

var year = 2022; Var STR =’ Beijing Winter Olympics in ‘+ year + year ‘; Note: year means to break the link; The new VERSION of ES has added the backquotation notation to make it easier to interpolate variables, which will be introduced in the next class.

Empty strings: Sometimes you need to use empty strings, just write closed quote pairs.

var str =’ ‘;

The length property of the string:

The length attribute of a string represents the length of the string.

‘I like JS’. Length //5

‘ ‘.length //0

Common methods for strings:

A “method” is a function that can be invoked, and strings have rich methods.

methods function
charAt() Gets the specified position character
substring() Extract the substring
substr() Extract the substring
slice() Extract the substring
toUpperCase() Uppercase the string
toLowerCase() Change the string to lowercase
indexOf() Retrieve string

1. The charAt () method

The charAt() method retrieves the character at the specified position.

'I like JS, I like HTML'.charAt(0)  / / 'I'
'I like JS, I like HTML'.charAt(11)  //'T'
'I like JS, I like HTML'.charAt(74)  / /"
Copy the code

2. The substring () method

The substring(a, b) method yields a substring from a to B (excluding B).

'I like JS, I like HTML'.substring(3.5)  //'JS'
'I like JS, I like HTML'.substring(10.14)  //'HTML'
Copy the code

The substring(a, b) method, if it omits the second argument, returns the substring up to the end of the string.

'I like JS and I like HTML'. Substring (6) //' I like HTML too'

In substring(a, b),a can be larger than B, and the order of digits is automatically adjusted to the first decimal.

'I like JS, I like HTML'. Substring (5,3) //'JS'

3. The substr () method

Substr (a, b) yields a substring of length B starting at a.

'I like JS and I like HTML'. Substr (3,2) //'JS'

In substr(a, b), b can be omitted to indicate the end of the string.

'I like JS, I like HTML'. Substr (3) //'JS, I like HTML'

In substr (a, b), a can be negative, representing the reciprocal position.

'I like JS and I like HTML'. Substr (-4,2) //'HT'

4. The slice () method

The slice(a, b) method yields a substring starting at A and ending at B (excluding b).

'I like JS and I like HTML'. Slice (3,5) //'JS'

The argument a to slice(a, b) can be negative.

'I like JS and I like HTML'. Slice (-4,-1) //'HTM'

In slice(a, b), parameter A must be less than parameter B.

'I like JS and I like HTML'. Slice (5,2) //'

5. Substring (). Substr () and slice() comparison summary

Substring (a, b) and slice(a, b) function basically the same, both get substrings from a to B (excluding B), the difference is:

(1) Substring () can automatically swap two argument positions, while slice() can’t; The slice() argument a can be negative, but substring() can’t.

(2) The parameter b in substr(a, b) is the substring length, not the position number

6. ToUpperCase () and toLowerCase ()

ToUpperCase () is capitalized

Change toLowerCase() toLowerCase

'i love you'.toUppercase( );//"I LOVE YOU"

'IMOOC' .toLowerCase();//"imooc"
Copy the code

7. IndexOf () method

The indexOf() method returns the first occurrence of a specified string value in the string. If the string value to retrieve is not present, it returns -1.

'abcdeb' .indexOf('b')/ / 1

'abcdeb' .indexOf('de')/ / 3

'abcdeb'.indexOf('m')/ / 1
Copy the code

Boolean Specifies a Boolean type

There are only two Boolean values: true and false, representing true and false, respectively.

typeof true; //boolean

typeof false; //boolean

5, Undefined type

The default value of an unassigned variable is undefined, and undefined is of undefined type.

That is, undefined is a value and a type that has only one value of its own.

typeof undefined; //undefined

6. Null type

Null means “empty”, it is “empty object”. When object destruction, array destruction, or deletion event listeners are required, they are usually set to NULL.

This is especially important when using Typeof to detect null values that result in object.

typeof null; //object

Type and Typeof test results do not always correspond, for example, arrays that typeof test results are object.

JavaScript can look “full of holes” and must be memorized. These points are often tested in interviews.

7. Data type conversion

1. Other values → numbers

(1) Use the Number() function

Strings → numbers, pure number strings can become numbers, strings that are not pure numbers will become NaN.

Number('123');/ / 123

Number('123.4');/ / 123.4

Number('123');//NaN

Number('2e3');/ / 2000

Number(' ');/ / 0
Copy the code

Boolean value → number

True becomes 1 and false becomes 0.

Number(true);/ / 1

Number(false);/ / 0
Copy the code

Undefined and NULL → number: undefined becomes NaN and null becomes 0.

Number(undefined);//NaN

Number(null);/ / 0
Copy the code

(2) Use parselnt()

The parselnt() function converts a string to an integer.

parseInt('3.14');//3 parselnt() will automatically truncate all characters after the first non-numeric character

parseInt( '3.14 is PI ');//3 All text will be truncated

parseInt('PI is 3.14'); If the string does not start with a number, it is converted to NaN

parseInt('3.99'); // 3 Parselnt () is not rounded
Copy the code

ParseFloat () converts a string to a floating point number.

parseFloat('3.14');//3.14 parseFloat() can convert a decimal string to a numeric decimal

parseFloat('3.14 is PI ');//3.14 parseFloat0 will automatically truncate all characters after the first non-numeric character and non-decimal point

parseFloat('PI is 3.14');If the string does not start with a number, it is converted to NaN

parseFloat('3.99');//3.99 is not rounded
Copy the code

2. Other values → String

(1) Use the String() function

Number → String:

Changes to a string that looks the same. Scientific notation and non-decimal numbers are converted to decimal values.

string(123); / / '123'

string(123.4);/ / '123.4'

String(2e3);/ / '2000'

string(NaN);//'NaN'

String(Infinity);//'Infinity'

String(0xf);/ / '15'
Copy the code

Boolean value → string:

Changes to a string that looks the same

String(true);//'true'

string(false);//'false'
Copy the code

Undefined and null→ string:

Changes to a string that looks the same

string(undefined);//'undefined'

String(null);//'null'
Copy the code

(2) Use the toString() method

Almost all values have a toString() method, which converts the value to a string.

3. Other values → Boolean values

(1) Use the Boolean() function

Number → Boolean value

0 and NaN are converted to false, and all other numbers are converted to true.

Boolean(123);//true

Boolean(0);//false

Boolean(NaN);//false

Boolean(Infinity);//true

Boolean(-Infinity); //true
Copy the code

Boolean → Boolean

Change the empty string to false and everything else to true.

Boolean(', ');//false

Boolean(" ABC ");//true

Boolean('false');//true
Copy the code

Undefined and null→ Boolean

To false

Boolean (” undefined “); //false

Boolean (” null “); //false

8. Small case: Small adding calculator

Use the prompt() function to pop up an input box that asks the user to enter two numbers.

The user input two numbers to add, but because the user input is a string, it must be converted to a number before it can add.

Finally, the result is displayed with alert().

Common computer program execution steps:

User input -> computer processing -> display results

Complex data types

In addition to basic type values, there are complex data types in the JS world. Such as:

[1, 2] {a: 1,b: 2} function () {

Complex data types are “reference types,” whose properties will be covered in array 1.

10. Key points

1. What are the basic type values in JavaScript? What are their Typeof detection results?

2. What are the following special values :①NaN ②undefined ④null

3. Conversion methods and conversion rules of various types of values

11. Difficult content

1. What is the result of the following expression?

The parseInt (‘ 3.6 ‘+’ 5.1 ‘); / / 3

Boolean( ‘false’); //true

0/0; //NaN

4/0; //Infinity

2. Tell the difference between the substring().substr () and slice() methods

“Abcde”. Substr (1, 3); / / “BCD” “abcde”. The substring (1, 3); / / “BC” “abcde”. Slice (3, 2); / / “” heavy” abcde “. The substring (3, 1); //”bc”

Expressions and operators

Expressions and operators

Type of expression: arithmetic; Relationship; Logic; The assignment; Comprehensive.

2. Arithmetic expressions

The operator meaning
+ add
Reduction of
* take
/ In addition to
% Take more than

Addition, subtraction, multiplication, and division: the signs for addition and subtraction are the same as in mathematics. Multiplication is an asterisk and division is a /.

By default, multiplication and division take precedence over addition and subtraction; Parentheses can be used to change the order of operations if necessary.

Two functions of the plus sign: The plus sign has two functions: addition and hyphen.

If the operands on both sides of the plus sign are numbers, it is “plus”; otherwise, it is a hyphen.

1+2 / / 3

1+'2' / / '12'

'1'+'2' / / '12'
Copy the code

Take over operations

Also called “modular operation”, denoted by the percent sign “%”.

A % b is the remainder of a divided by b, it doesn’t care about the integer part, it only cares about the remainder.

Implicit type conversion

If an operand involved in a math operation is not numeric, JavaScript automatically converts the operand to numeric. The essence of an implicit conversion is to call the Number() function internally.

3*'4' / / 12

true + true / / 2

false + 2 / / 2

3*'two days' //NaN
Copy the code

The IEEE754

In JavaScript, the math of some decimals is not very precise.

0.1 + / 0.2/0.30000000000000004

JavaScript uses the IEEE754 binary floating-point arithmetic standard, which can cause “loss of precision” problems with certain decimal operations.

Workaround: When performing decimals, call the toFixed() method of the number to preserve the specified decimal number.

(0.1 + 0.2) toFixed (2) / / “0.30”

Number ((0.1 + 0.2) toFixed (2)) / / 0.3

Power sum, square root

There are no exponentiation, square root operators in JavaScript. The calculations need to be performed using the relevant methods of the Math object.

(2, 3) / / 8 math.h pow

Math.h pow (3, 2) / / 9

Math.sqrt(81) //9

Math.sqrt(-81) //NaN negative numbers cannot be squared

Round up and round down

Math.ceil() rounded up; Math.floor) is rounded down.

Math. Ceil (2.4) / / 3 math.h floor (2.4) / / 2

Math. Ceil (2.4) / / – 2 math.h floor (2.4) / / 3

Math.ceil(2) //2 Math.floor(-2) //2

3. Relational expressions

Relational operator

The operator meaning
> Is greater than
< Less than
> = Greater than or equal to
< = Less than or equal to
= = Is equal to the
! = Is not equal to
= = = All is equal to the
! = = Not all equal

Greater than and less than: greater than > and less than < are mathematically identical.

The greater than or equal operator is >=, and the less than or equal operator is <=.

8>5 //true

7<4 //false

8> =7 //true

8> =8 //true

8< =8 //true

8< =11 //true
Copy the code

Determine equality

If you want to compare two values for equality, you should use the == operator.

JavaScript medium = denotes assignment, not equality. Equality should be determined using the == operator.

3= =3 //true

3= = =3 //true

3=3 // Error statement
Copy the code

Equality and congruence

The two equal == operators do not compare the types of values; they do an implicit conversion to compare the values for equality.

The three equal === operators compare not only the same values but also the same types.

5= ='5'; //true
5= = ='5'; //false

1= =true //true
1= = =true //false

0= =false //true
0= = =false //false

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

Since the NaN. Etc

NaN is a special numeric type value that also has special results when compared with ==.

NaN= =NaN //false

NaN= = =NaN //false
Copy the code

How do I tell if a variable is NaN

The isNaN() function can be used to determine whether a variable value isNaN.

isNaN(NaN) //true

isNaN(5) //false
Copy the code

But isNaN() is also unusable, and it works like this: isNaN() returns true whenever the result of the execution of Number) isNaN.

isNaN(undefined) //true

isNaN('three days') //true

isNaN(null) //false
Copy the code

The equality relation of special values

null == undefined //true

null == 0 //false

NaN ==NaN //false

Unequal and incongruent

! = means not equal,! == indicates incongruence.

5! =6 //true

5! = =6 //true


5! ='5' //false

5! = ='5' //true
Copy the code

4. Logical expressions

Logical operator

The operator meaning
! non
&& with
|| or

1. The operation

! Stands for “not”, can also be called “inverse operation”. ! Is a “unary operator” that requires only one operand.

The result of transpose must be a Boolean

!true //false
!false //true

!0 //true
!undefined //true
!' ' //true
!'imooc' //false!!!!!true //ture!!!!!0 //false!!!!!' ' //false!!!!!'imooc' //true !! Represents a Boolean value for the value
Copy the code

2. With operation

&& means “and”, called “and operation”, formula: true is true. (The following formula also conforms to short-circuit calculation)

true && true //true
true && false//false
false && true//false
false && false//false
Copy the code

3. Or operation

| | said “or”, called “or operations,” mantra: there is really true. (The following formula also conforms to short-circuit calculation)

true || true //true
true || false//true
false || true//true
false || false//false
Copy the code

4. Short-circuit calculation (short-circuit calculation is very useful in working programming, which will be explained in the next course)

(1) A &b are true.

If a is true, b is true, and b is false, the total result is false. If A is false, don’t look at B, it is “short-circuited”. A && B operation: A true, expression value is B; A false, expression value is a.

3&&6 / / 6
undefined&&15 //undefined
15&&undefined //undefined
null&&2 //null
' '&&16 / /"
NaN&&undefined //NaN
Copy the code

(2) a | | b is true is true.

If a is true, b is “short-circuited”.

If A is false, the total result is true if B is true, and the total result is false if B is false.

A | | b operation: a true, the expression values for a; A is false and the expression value is b.

3||6 / / 3
0||6 / / 6
null||undefined //undefined
'a'||'b' //'a'
NaN||null //null
Copy the code

5. Logical operation sequence

The priority of logical operations is: not → and → or.

!true||true //true
3&&4||5&&6 / / 4
Copy the code

5. Assignment expressions

The assignment operator

The operator meaning
= The assignment
+ = – =, * = / = % = Quick assignment
++ On the operation
Since the subtraction operation

In JS, = represents assignment, == determines whether it is equal (not the type), === determines whether it is congruent.

The assignment operator assigns the value to the right-hand side of the equal sign to the variable to the left.

Assignment also produces values

The assignment also produces a value, and the value after the equal sign will be the “value of the assignment.”

var a;

console.log(a = 4); / / 4
Copy the code

This means that assignment operators can be used continuously.

var a, b,c;

a = b = c = 15;

console.log(a) ; / / 15

console.log(b) ; / / 15

console.log(c) ; / / 15
Copy the code

The increment/decrement operators ++ and — are increment/decrement operators that add or subtract 1 from themselves

var a = 3;
a++;
console.log(a); / / 4
Copy the code

What’s the difference between a++ and a++ a? Plus plus a plus a.

	var a=3;
    var b=a++;
    console.log(b);/ / 3
    console.log(a);/ / 4

    var a=3;
    var b=++a;
    console.log(b);/ / 4
    console.log(a);/ / 4
Copy the code

6. Synthetic expressions

Operation order: non-operation → mathematical operation → relational operation → logical operation (non-numerical logic).

5<3+3 //true
3>2 && 8>3+4 //true
3>2 && 8>3+5 //false
!13 <5-3 //true
!13 <5-5 //false
Copy the code

Case study: Leap year judgment

A simple method for calculating leap years in the Gregorian calendar (one of the following conditions is required) 1. Divisible by 4 and not divisible by 100. 2. It’s divisible by 100 and it’s divisible by 400.

7. Key points

1. What kinds of expressions are there? What are the operators for each expression?

2. What is the order of operations in each expression? What is the order of synthesis?

8. Difficult content

1. What is short-circuit calculation? What is the result of 3&&13? 3 | | 13?

13, 3

2. What’s the difference between a++ and ++a?

A ++ is going to be plus, plus +a is going to be plus.

var a = 3;

var b = 4;

alert(a++ + b++ + ++a + ++b);
Copy the code

A ++, alert = 3; And then a++, so a is equal to 4;

B ++, alert is 4, and then B ++, so b=5;

++a =4+1=5;

+ + b, b = 5 + 1 = 6;

So 3 plus 4 plus 5 plus 6 is 18;