JavaScript course Lesson 4 of 6

JavaScript from zero: const does not freeze the fields

const stops a new assignment to the name. It does not freeze the fields. A spread copies the drink. The original stays 450. The tipped copy is 540.

Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.

Back to top

const item means item will not be pointed at another object. item = somethingElse is an error. item.cents = 540 is allowed, and it changes the object everyone else can see. A 20 percent tip should be a new total, not a rewritten menu price. Copy the object and change the copy.

const protects the name, not the fields#

const means the binding item will not be pointed at a different object. The object's properties are still writable. The spread builds a new object, copies the properties, and sets cents to 540 on the copy only. 540 is 450 plus a 20 percent tip, 90 cents. item.cents remains 450, which is what the program prints first. If the code had assigned item.cents = 540 instead, both readers of item would see the tip baked into the menu price, and const would not have stopped it. Copy when the next state should leave the previous state alone.

The tip is a different object
  1. item450
  2. tipped540
const item = { name: "latte", cents: 450 };
const tipped = { ...item, cents: 540 };
console.log(item.cents, tipped.cents);
450 540

The three dots copy the fields#

...item puts name and cents onto a new object. Writing cents: 540 after that replaces cents on the new object only. item.cents stays 450. tipped.cents is 540. The menu still says $4.50. The bill says $5.40.

If you had written item.cents = 540, there would be one object and the old price would be gone. No error. The tip is to notice when a function receives an object and assigns to its fields. The caller sees those assignments. Pass a copy when the caller should keep the original.

The copy is shallow#

...item copies each field's value. A number and a string are copied outright. If a field were another object, both owners would share it. This drink has no inner object, so the copy is the whole value. The next lesson is what happens when you take a method off the object and call it alone.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.