Two classic interview questions about JavaScript value types and reference types
Question 1
First, let’s try your hand at a small test. Please look at the first question.
let a = {
x: 10
}
let b = a
a.x = 20
console.log(b.x)
a = {
x: 30
}
console.log(b.x)
a.x = 40
console.log(b.x);
So what is the output of the above code?
answer list:
Idea: In memory, basic data types are stored on the stack, while reference data types are stored on the heap.
Let’s explain it in detail below:
- First define an object a, which has an attribute x with a value of 10, and then b=a, so that a and b point to the same object;
- Next, a modifies the x attribute value of the object to 20;
- Then, a new object { x: 30 } is assigned to a;
- Finally, the x attribute of a is modified to 40.
At this point, I believe everyone can clearly understand the output results! Let’s look at the second question next.
Question 2
let a = {
n: 10
}
let b = a
a.x = a = {
n: 20 }
console.log(a.x)
console.log(b.x);
Without further ado, let’s get straight to the answer.
Next, let’s analyze the specific process:
- First, a points to an object {n:10}, and assigns a to b. At this time, a and b both point to the same object;
- Next let’s look at the most important line of code:
a.x = a = {
n: 20 }
.
The operator takes precedence over the =
operator. In this case, the .
operation is performed first, that is, at the address of a
Put the x
attribute inside (different people have different understandings here. I temporarily understand that the attribute name is not a variable and does not open up new space). At this time, the assignment operation is performed, and the assignment is from right to left. , one assignment, that is, assigning {n:20}
to a
and a.x
, at this time a
points to the new address {n:20}
, and a.x
also points to the new address {n:20}
.