Important: Every blog post repeats ๐๐๐
The formula ๐คจ : four bases, two empty objects, and five falsy values.
Seven data types
- number string bool symbol
- null undefined
- object
Five falsy value
- null undefined
- 0 NaN
- “(empty string)
preface
When executing a JS function, the result will be different depending on the position of the function.
Let’s look at a few examples of how the timing of a function’s execution can affect the result.
The body of the
Case 1
let a = 1
function fn(){
console.log(a)
}
Copy the code
Tang’s monk: apprentice son, excuse me on regular meeting print out how many?
Wukong: I don’t know, because you didn’t call function fn.
Case 2
let a = 1
function fn(){
console.log(a)
}
fn()
Copy the code
Tang’s monk: apprentice son, excuse me on regular meeting print out how many?
Obviously, it is 1.
Example 3
let a = 1
function fn(){
console.log(a)
}
a = 2
fn()
Copy the code
Tang’s monk: apprentice son, excuse me on regular meeting print out how many?
Shaseng: Because fn is executed after a=2, print 2.
Example 4
let a = 1
function fn(){
console.log(a)
}
fn()
a = 2
Copy the code
Tang’s monk: apprentice son, excuse me on regular meeting print out how many?
White dragon: Comparing with example 3, we can see that fn is called first, so it will print 1.
The first few examples are relatively simple, I believe you can answer. So now let’s upgrade the difficulty, look at this:
Is the
Different timing, different results
let i = 0
for(i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}// Output six 6's
Copy the code
The for loop is in the main thread, and setTimeout is an asynchronous method. In the task queue, the task queue will execute only after the main thread has finished executing. When the for is finished, the I value is already 6, so the result is 6. So how do I print 0 minus 5.
for(let i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0)}Copy the code
This is one of the things that JS changed later for new developers. Let the code do what the new guy wants. So what else can we do to print 0 to 5?
This can be done by self-executing functions
for (var i = 0; i <= 5; i++) { ! (function (j) {
setTimeout(function print() {
console.log(j);
}, 0);
})(i);
}
Copy the code
- By setTimeout the third argument
for (var i = 0; i < 6; i++) {
setTimeout((i) = > console.log(i), 0, i);
}
Copy the code
It took me two months to understand let
As my level is limited, if there is an inaccurate description of the place please give me a message, welcome to exchange ~
This article is a personal original, reproduced please indicate the source.