JavaScript course Lesson 2 of 6

JavaScript from zero: an object has fields

An object groups named fields. A latte has a name and a price in cents. The program prints latte $4.50.

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

An object is a set of names and values. name holds the drink. cents holds the price. You read a field with a dot. One object keeps the two facts together so a function can take the drink instead of two loose arguments.

An object is a bag of properties#

An object literal allocates one object and stores the properties you wrote. item.name looks up the property. Missing properties are undefined, not an error. const item stops you from rebinding the name item. It does not stop item.cents = 0, because the object is mutable. Two literals are two objects, even when the fields look the same. Equality of objects is by identity unless you compare the fields yourself.

The properties are the drink
  1. namestringlatte
  2. centsnumber450
const item = { name: "latte", cents: 450 };
const frac = String(item.cents % 100).padStart(2, "0");
console.log(item.name + " $" + Math.floor(item.cents / 100) + "." + frac);
latte $4.50

The braces build the object#

{ name: "latte", cents: 450 } is the object, and item is the name for it. item.name is "latte". item.cents is 450, the cents, not the dollars. Math.floor and % turn those cents into $4.50 only when you print. A missing field is undefined. item.price would print undefined, because the field you defined is cents.

const means you will not point item at a different object later. It does not freeze the fields. The lesson after the class shows that, with a copy. For now, treat the object as the drink you just made, and read the fields by the names you wrote.

Pass the object onward#

A function function price(item) { return item.cents; } takes the whole drink. The caller cannot swap the name and the price by putting the arguments in the wrong order. There is one argument. The next lesson moves that job onto the object as a method.

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.