Mutation Flashcards

1
Q

Can objects be inside or nested in other objects in our mental model?

A

Objects might appear “nested” in code, but in our universe, each object is completely separate. An object cannot be “inside” of another object! If you have been visualizing nested objects, now is the time to change your mental model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can two different objects have a property wiring to the same object?

A

Yes!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can properties ever point to variables or other properties?

A

Nope! A property always points to a value! It can’t point to another property or a variable. In general, all wires in our universe point to values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s a common gotcha when mutating objects?

A

Because non=primitives (such as objects or functions) are passed as reference changing them can change the value of all other variables or properties referencing that object.

This is why the intuition of objects being “nested” is so wrong! It makes us forget that there may be many objects pointing to the object we changed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do we get around the common issue of mutating objects that are potentially used elsewhere?

A

Break the link! Create a new object using the values of the previous using something like destructuring or object.assign. Note if there are nested wires to other objects we’d need something like a deepclone from lodsash.

It’s worth noting that mutating new objects that you’ve just created is always okay because there are no other wires pointing to them yet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Once you set a const variable can you mutate its contents?

A

If the contents are one of our non-primitive values such as an object or a function then yes you can mutate it! You just can’t reassign it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does const do?

A

Const prevents variable reassignment—not object mutation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What will the following log?

const spreadsheet = { title: 'Sales' };
const copy = spreadsheet;
copy.title = copy.title + ' (Copy)';

console.log(spreadsheet.title); // ???

A

// Sales (Copy)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What will the following log?

let ilana = {
  address: { city: 'New York' }
};
let place = ilana.address;
place = { city: 'Boulder' };
let abbi = {
  address: place
};

console.log(ilana.address.city); // ???

A

// New York

How well did you know this?
1
Not at all
2
3
4
5
Perfectly