1. What is the output?
function sayHi() {
console.log(name)
console.log(age)
var name = 'Lydia'
let age = 21
}
sayHi()
Copy the code
The answer is: undefined and error. Because var defines variables that have the effect of variable promotion, but only the promotion of the variable declaration, no assignment, so undefined, let defines variables that are promoted, but not initialized, before the initialization call will report an error, this is temporary dead zone.
2. What is the output?
for (var i = 0; i < 3; i++) {
setTimeout(() = > console.log(i), 1)}for (let i = 0; i < 3; i++) {
setTimeout(() = > console.log(i), 1)}Copy the code
The answer is: 333 and 012, because of the event loop mechanism of JS, setTimeout belongs to the macro task, and can not be executed until the synchronized code is finished. Var here defines a global variable, so after the synchronized code is finished, I has become 3, so three 3’s are printed, but the variables defined by let form a block level scope. So it’s 0, 1, 2
3. What is the output?
const shape = {
radius: 10.diameter() {
return this.radius * 2
},
perimeter: () = > 2 * Math.PI * this.radius
}
shape.diameter()
shape.perimeter()
Copy the code
A: The output is 20 and NaN, because this in diameter refers to radius in shape, but perimeter is an arrow function so when we call perimeter, this doesn’t refer to shape, It’s the scope around it (in this case, window).
4. What is the output?
+true;
!"Lydia";
Copy the code
Solution: the + sign changes true to 1, and the + sign tends to return a value, but! It tends to return a Boolean value, because “Lydia” is real, so it’s false.
5. Which one is true?
const bird = {
size: 'small'
}
const mouse = {
name: 'Mickey'.small: true
}
Copy the code
The answer: A) if mouse has the property of bird, which it does not, it is invalid. B) if mouse has the property of bird, which it does not, it is invalid. A.