The preface
Before we start chapter 3, let’s review Chapter 2: Introducing script Elements. Introducing JavaScript to HTML and using noScript elements when scripts are disabled or not supported. Chapter 3, then, begins with a serious understanding of the language basics of JavaScript. In fact, we can do this part of the front-end, but there are some code style and did not notice the point, missed, is not better. All right, chapter three.
MIND
grammar
I used to learn JAVA, JavaScript syntax is very similar to it, very friendly. Here’s a quick look at the syntax:
- Case sensitive
- Identifier: The first character must be in
[' letter ',' underscore (_)',' dollar sign ($)']
, recommended useHump caseForms, such ascolorList
- Note: C language style, “//” single line, “/* */” multiple lines
- Strict mode: use
use strict
Set strict mode - Statement: It is recommended to add a semicolon to the end of the statement
- Keywords and Reserved words: Cannot be used as identifiers or property names. Click to view
Variable declarations
A variable is nothing more than a command placeholder to hold arbitrary values
JavaScript variable types are not as rigid as Java, they are “eel” variants that can be easily changed at any time. Declaring variables is also relatively easy and much more convenient. There are three keywords to declare variables: var, let, and const.
var
You can use var to declare variables arbitrarily, yes, very arbitrarily:
- You can leave variables uninitialized
- Function scope is generated: a declared variable becomes a local variable of the function that contains it
- Function declaration without var, the variable will become a global variable, not recommended
- Variables can be declared repeatedly
- Variable promotion exists: all declarations are promoted to the top of the function scope, and the declaration is preceded by undefined.
let
Let is new to ES6. It is similar to var, but is better for declaring variables than let, with the following features
- You can also leave variables uninitialized
- Variables cannot be declared repeatedly in a block scope
Let declarations build block scope and do not allow redundant declarations, which can lead to errorsCopy the code
- Does not cause variable promotion:
The moment before a LET declaration is called a temporary dead zone, in which references to any variable declared later will throw a reference errorCopy the code
- Declaring variables in a global scope does not become global variables
- There is no variable promotion
The scope of let is block and cannot be declared repeatedly. There are no variables with the same name that need to be declared in the top scopeCopy the code
- Suitable for iterating variables in a for loop,
Let declares an iteration variable, which declares a new iteration variable behind the scenes for each iteration loopCopy the code
const
Const has the same root as let, but is used to declare constants and has the following characteristics:
- Unlike var and let, variables must be initialized when declared
- The declaration limits references only to the variable to which it points
- If the reference is a non-object, it cannot be modified
- If you reference an object, you can modify the internal properties of the object, but not the object
- Const is suitable for for-in and for-of loop variables
The statement style
- By not using var, problems such as variable promotion and repeated declarations can be avoided
- Const takes precedence over let. Const can keep variables unchanged and detect illegal assignments ahead of time. If you need to change it in the future, you can change it to let declaration.
The data type
There are six basic data types in the book: Undefined, NULL, Boolean, Number, String, and Symbol. In fact, Bigint is new to ES10. There is also the complex data type Object. Now to introduce them all
typeof
First, the detection tool tyoeOF is one of the methods to detect data types. The return rules are as follows:
- Undefined and Undeclared => “Undefined”
- Boolean => “boolean”
- String => “string”
- Number => “number”
- Null and Object => “Object”
- Function => “function”
- Symbol => “symbol”
- ES10 新增的 Bigint => “bigint”
Undefined
Undefined has a single value, which is the special value Undefined, to formalize the difference between a null pointer and an uninitialized variable.
When the var or let declaration described above is used but not initialized, the variable is given undefined. Although given this value, it is not recommended to explicitly assign this value to a variable
The difference between undefined and undeclared
- Description: undefined is declared not yet and undeclared is undeclared
- References: undeclared variable references will raise an error while undefined does not
Also, using Typeof detection, both of which return “undefined”, it is recommended to initialize variables when declaring them to avoid typeof confusion and thus know which variables are undeclared.
Null
The Null type is also a value, the special value Null. Logically, a null value represents an empty object pointer, which is why passing a NULL to typeof returns “Object”.
It is worth noting:
- When defining variables that will hold object values in the future, it is recommended to use NULL for initialization
- Undefined is derived from null,
null == undefined
Null is different from undefined
- Meaning: NULL represents an object pointer, undefined represents an undefined declaration
- Identifier: undefined is not a reserved word and can be used as a variable name (not recommended). Null is a reserved word
- Typeof: undefined returns “undefined” and null returns “object”
Boolean
Boolean is used frequently and has only two values: true and false. Other types can be converted to Boolean types through the Boolean() function.
Number
The Number type uses the IEEE754 format to represent integers and floating point numbers.
Into the system
The Number type has different numeric literal formats:
- Decimal: the most basic, as
10
- Octal: the prefix is
0
或0o
, such as0o12
- Hexadecimal: the prefix is
0X
, such as0XC
Floating point Numbers
To define a floating point value, the value must contain a decimal point, and there must be at least one digit after the decimal point.
It has the following characteristics:
- Floating-point numbers have twice as much storage space as integers, so ECMAScript tries to convert values to integers
- The value is IEEE754, and a rounding error occurs
0.1 + 0.2 = 0.300 000 000 000 000 04
The range of values
- Minimum value:
Number.MIN_VALUE => 5e-324
- Maximum value:
Number.MAX_VALUE => 1.797 693 134 862 315 7E +308
- Plus or minus infinity: out of range used
Infinity
和-Infinity
Said,isFinite()
Function test
NaN
NaN represents not a valid value and is used to indicate that an operation that should have returned a value failed.
It has the following characteristics:
- Operations involving NaN always return NaN
- NaN is not equal to anything, including itself
- using
isNaN()
detection
Numerical transformation
ParseInt (); parseFloat(); parseFloat(); parseFloat();
First, parseInt() has the following characteristics:
- If the first character is a numeric character, plus, or minus, continue to monitor each character until the end of the string or a non-numeric character is encountered, such as “1234ABCD” converted to “1234”
- If the first character is not, return NaN immediately, including null characters
- A second argument can be passed to specify the base, between 2 and 36, and not return NaN
Next, parseFloat() is also special:
- Always ignore the 0 at the beginning of the string
- Only decimal parses; base cannot be specified
- Other bases return 0
String
The String data type represents zero or more 16-bit Unicode character families.
Strings have the following characteristics:
- Use double quotation marks (“), single quotation marks (‘), and backquotation marks (‘), but do not mix them, for example, ‘string ‘.
- The transfer sequence represents one character, and only one character
- Strings get their length through the length attribute, but the length value may be inaccurate if the string contains double-byte characters
- Strings are immutable, and modifications destroy the original string and then save the new string to the variable
Template string
Note the new template string in ES6, which is really useful:
- Defining HTML templates
let pageHtml = ` ` Copy the code
- String interpolation
let value = 1; console.log(`value is ${value}`) // value is 1 Copy the code
Symbol
Symbol is used to ensure that object attributes use unique identifiers without the risk of attribute collisions.
This data type is newly added in ES6. For a brief understanding, a new chapter on Symbol should be added.
define
Initializing with Symbol(), you can pass in a string as a description that has nothing to do with the Symbol definition or Symbol itself. This description is used in combination with symbol.for () and symbol.keyfor ().
let sym = Symbol(a);/ / initialization
let sym2 = Symbol(2); // Pass description 2
Copy the code
A global Symbol
Symbol.for() performs an idempotent operation on each string key: first checks to see if the Symbol described is in the global registry, generates the global Symbol if not, and returns the Symbol otherwise.
Symbol.keyfor () is used to check whether the Symbol is global, if return Symbol description, otherwise return undefined.
Use Symbol as the attribute
This is the key to Symbol: You can use Symbol wherever you can use a string or a value as an attribute
Bigint
MAX_VALUE is an integer greater than 2^ 53-1. A Bigint is defined by adding n after the integer. Unsigned right-shifted Bigint is not supported, and the + operator cannot be used with non-bigint types.
Object
An object is a collection of data and functionality.
In JavaScript, “everything is based on objects” because Object is the base class of all objects, and “descendants” are created using the new operator. Have properties and methods that are common to any of the following objects:
- Constructor: The function used to create the current object
- HasOwnProperty (propertyName) : Used to check whether the current object instance has a given property. PropertyName must be a string
- IsPrototypeof (object) : Used to determine whether the current object is the prototype of another object
- PropertyIsEnumerable (propertyName) : Used to determine if a given property can be enumerated in a for-in statement. PropertyName must be a string
- ToLocaleString () : Returns a string representation of an object that reflects its localized execution environment
- ToString () : Returns a string representation of an object.
- ValueOf () : Returns a string, numeric, or Boolean representation of an object, usually the same as the toString() return value
Type conversion
Turns a Boolean
Use Boolean() conversions
The data type | true | false |
---|---|---|
String | Non-empty string | An empty string |
Number | Nonzero value | 0, NaN |
Object | All the objects | There is no |
Null | There is no | null |
Undefined | There is no | undefined |
Turn Number
Use the Number() function to convert
- Boolean, true to 1, false to 0
- Null returns 0
- Undefined,转为 NaN
- String:
- Numeric characters are converted to numbers
- An empty string is converted to 0
- Non – numeric characters are converted to NaN
- Object:
- ValueOf () is first called to the base type, and then converted
- If converted to NaN, the base type is converted using toString()
- It still can’t be converted, it will get an error
Turn the String
Use the String() function to convert
- Number, converted to a string
- Boolean, convert to “true”, “false”
- Null to “Null”
- Undefined = Undefined
- Object:
- If the Object’s toString() method is not modified, the built-in property [[class]], such as “[Object Object]”, is returned.
- If there are modifications, the modified toString() method is implemented and the return value of the method is returned
The operator
Operators focus on special rules
Unary operator
- Increment/decrement: Increases or decrement values are returned, but prefixes versus suffixes change the value of a variable before the statement is evaluated, while suffixes change after the statement is evaluated
- Unary addition and subtraction: For non-numeric operations, the Number() transformation function is used
An operator
This part is very hardcore, just watch it and learn it later
The bitwise not (~
)
The effect is to return the complement of a numeric value, the final effect is to negate the value and subtract one, compared to the normal operation based on the bitwise is faster
let num = 6;
console.log(~num); / / - 7
Copy the code
Bitwise and (&
)
The effect is to align each bit of two numbers, and then perform the response and operation on each bit based on the rules in the truth table. The final effect is to return 1 if both bits are 1 and 0 if either bit is 0.
let res = 25 & 3;
console.log(res) / / 1
// 25 => 0000 0000 0000 0000 0000 0000 0001
// 3 => 0000 0000 0000 0000 0000 0000 0000 0011
// AND=> 0000 0000 0000 0000 0000 0000 0000 0001
Copy the code
The bitwise or (|
)
Returns 1 if at least one digit is 1 and 0 if two digits are 0;
let res = 25 | 3;
console.log(res) / / 27
// 25 => 0000 0000 0000 0000 0000 0000 0001
// 3 => 0000 0000 0000 0000 0000 0000 0000 0011
// AND=> 0000 0000 0000 0000 0000 0000 0001 1011
Copy the code
Bitwise xOR (^
)
Returns 1 only if the digit is 1
let res = 25 ^ 3;
console.log(res) / / 26
// 25 => 0000 0000 0000 0000 0000 0000 0001
// 3 => 0000 0000 0000 0000 0000 0000 0000 0011
// AND=> 0000 0000 0000 0000 0000 0000 0001 1010
Copy the code
Shift to the left (<<
)
Moves all bits of the value to the left by the specified number of bits
let num = 3; // Binary 11
console.log(num << 5) / / 96
/ / 1100000 = > 96
Copy the code
Signed shift right (>>
)
Left-shift inverse: Moves the 32 bits of the value to the right, preserving the positive and negative signs
let num = 96; // Binary 1100000
console.log(num >> 5) / / 3
/ / 11 = > 96
Copy the code
Unsigned right shift (>>>
)
Unlike the signed right shift, which adds 0 to the empty space, the unsigned right shift results in a different result when dealing with negative numbers
let num = -96; // 1111 1111 1111 1111 1111 1111 1101 0000
console.log(num >>> 5); / / 134217725
// 0000 0111 1111 1111 1111 1111 1111 1111 1101
Copy the code
Boolean operator
There are three “and/or” Boolean operators
Logic is not (!
)
The operator is converted to a Boolean based on Boolean() and then inverted
Logic and (&&
)
A logical sum is represented by two ampersand signs (&&), but does not necessarily return a Boolean value, as follows
- If both operands are Booleans, all is true and false is false
- Returns the second operand when the first operand is an object
- When the second operand is an object, the object is returned only if the first operand evaluates to true
- If an operand is null\NaN\undefined, that operand is returned
Logic or (||
)
- When both operands are Boolean, all false is false, and true is true
- The first operand evaluates to false and returns the second operand
- The first operand is an object that is returned
- The two operands are null\NaN\undefined and return these values
Multiplicative operator
The multiplicative operator includes three operators: multiplication, division, and modulus. The non-numeric operand is converted to a numeric value by Number() and then computed
Multiplication operator (*
)
multiplicand | The multiplier | return |
---|---|---|
The numerical | The numerical | Product or plus or minus Infinity |
NaN | other | NaN |
other | NaN | NaN |
NaN | NaN | NaN |
Infinity | 0 | NaN |
Infinity | Finite numbers that are not zero | Infinity in positive and negative form |
Infinity | Infinity | Infinity |
Division operator (/
)
dividend | divisor | return |
---|---|---|
The numerical | The numerical | Quotient or plus or minus Infinity |
NaN | other | NaN |
other | NaN | NaN |
NaN | NaN | NaN |
0 | 0 | 0 |
Finite values that are not zero | 0 | Plus or minus Infinity |
Infinity | other | Plus or minus Infinity |
The modulo operator (%
)
dividend | divisor | return |
---|---|---|
The numerical | The numerical | remainder |
Infinity | Limited value | NaN |
Limited value | 0 | NaN |
Infinity | Infinity | NaN |
Limited value | Infinity | dividend |
Exponential operator
** operator replaces math.pow () in ES7
console.log(Math.pow(3.2) / / 9
console.log(3支那2) / / 9
Copy the code
The additive operator
The addition operator (+
)
augend | addend | return |
---|---|---|
The numerical | The numerical | and |
NaN | other | NaN |
other | NaN | NaN |
NaN | NaN | NaN |
Infinity | Infinity | Infinity |
-Infinity | -Infinity | -Infinity |
Infinity | -Infinity | NaN |
+ 0 | + 0 | + 0 |
0 | + 0 | + 0 |
0 | 0 | 0 |
If an operand is of type non-number, there are rules: - Two numbers are strings, the latter concatenated to the end of the former - one is a string, convert the other operand to a string, concatenate - One is an object, a value, or a Boolean, call the toString() method of that value to get the string, and then evaluateCopy the code
The subtraction operator (-
)
minuend | reduction | return |
---|---|---|
The numerical | The numerical | poor |
NaN | other | NaN |
other | NaN | NaN |
NaN | NaN | NaN |
Infinity | Infinity | NaN |
-Infinity | -Infinity | NaN |
Infinity | -Infinity | Infinity |
-Infinity | Infinity | -Infinity |
+ 0 | + 0 | + 0 |
+ 0 | 0 | 0 |
0 | 0 | + 0 |
If an operand is of type non-number, there is a rule: ValueOf (); toString(); toString()Copy the code
Relational operators (<
,>
,< =
,> =
)
- The operands are all numerical values for comparison
- Operands are strings that compare the encoding of each character in the string
- If the operand has a value, the other operand performs the Number() conversion
- If the operand has an object, valueOf() is called to take the valueOf the object; if there is no valueOf(), toString() is called to take the string and compare
- Operands have Boolean values, which are converted to values and then compared
Equality operator
The operators are divided into equal and congruent operators
Equals and does not equal (= =
,! =
)
- One of the operators is a Boolean value that is converted to a value and then compared
- The first operator is a string and the other is a value. Try to convert the string to a value and compare
- The first operator is an object, the other is a non-object, and calls valueOf() of the object. If toString() is not called, then compares
null == undefined
- Null and undefined cannot be converted to other values for comparison
- If one of the operators is NaN, it is not equal
- Operators are all objects, comparing whether they refer to the same object
Congruence and incongruence (= = =
,! = =
)
The congruent operator does not convert operands for comparison and is preferred
Conditional operator
This is a ternary expression.
variable = boolean_expression ? true-value : false_value;
Copy the code
If boolean_expression is true, true-value is assigned to variable, and otherwise false-value is assigned to false_value.
The assignment operator
Num = num + 10 => num += 10, similar to many abbreviations
statements
- If: Calls the Boolean() conversion function. Block statements are recommended
- Do-while: The code in the loop body must be executed at least once before an exit condition is determined
- While: Test the condition first
- For: Use let to declare iterator variables that can be scoped within the loop
- For-in: Used to enumerate non-symbolic properties in an object. The order in which object properties are returned is not guaranteed. Usually used to traverse an object
- For-of: Elements used to iterate over an iterable, iterating in the order in which the iterator next() produces the elements referred to
- Break: Used to exit the loop, forcing the next statement to loop
- Continue: Used to exit the loop and execute the loop from the top
- With: Sets code scope to a specific object and is not recommended
- Switch: Executes statements based on case, which can be a constant, variable, or expression. It is recommended to add a break statement after each condition
function
Functions are a core component of any language because they can encapsulate statements and execute them anywhere, at any time.
The basic syntax is:
function functionName (arg0, arg1, ... , argN) { / / declare
statements / / statements
}
functionName(); / / call
Copy the code
The function returns a value using return. Note:
- Return is not mandatory
- Conditional returns are not recommended if there is a return.
- The function stops execution and exits immediately after the return statement
- If return does not have a value, undefined is returned
Also note the restrictions in strict mode:
- Functions cannot be named eval or arguments
- Function arguments cannot be called eval or arguments
- The arguments of two functions cannot have the same name
conclusion
Chapter 3 is more informative and intensive than the previous two chapters, focusing on JavaScript syntax, variable declarations, data types, operators, statements, and functions. Although most of the knowledge is well understood, it is important to pay attention to data type conversions and some operators. The next chapter covers variables, scopes, and memory.