Changing an object or replacing a reference?
How changing a property differs from assigning a variable, and what const prevents.
In the previous lesson, we examined two variables that refer to one object. Now we will compare two actions: changing an object property and assigning a different value to a variable.
const player = { hp: 100 };
let target = player;
target.hp = 50;
target = null;
// player.hp is 50; the object is still reachable
const player = { hp: 100 }creates an object and stores a reference to it inplayer.let target = playerassigns totargetthe same object value. Both variables now hold references to one object. This is not a reference fromtargetto the variableplayer: each variable provides access to the object independently.target.hp = 50accesses the object through the reference held bytargetand writes a new value to itshpproperty. The shared object changes, so bothtarget.hpandplayer.hpnow equal50.target = nullreplaces only the value oftarget. It now holdsnullinstead of a reference. The value ofplayerand the object itself stay the same; the object remains accessible throughplayer.
target.hp = 50
player
{ hp: 50 }target
The property changed. Both references remain.
target = null
player
{ hp: 50 }target
null
target no longer points to the object. player still does.
target has changed.