A passport for a cat
Objects, properties, the dot and brackets, in, Object.keys and ?..
const cat = { name: "Byte", age: 3, color: "grey" };
console.log(cat.name);
console.log(cat["age"]);
console.log(cat);Why not four variables? Because there are many cats. You could, of course, keep two arrays, names and ages, and agree that Mittens's age sits at the same index as her name. That works right up to the first deletion: you strike out a name, forget the age, and the whole archive slips by one cat. An object keeps one cat's fields together: you can only pass it, delete it or move it as a whole.
const cats = [
{ name: "Byte", age: 3 },
{ name: "Mittens", age: 2 },
];
for (const cat of cats) {
console.log(cat.name + " — " + cat.age + " y.o.");
}
console.log(cats[1].name);The essentials of objects:
- properties are listed with commas:
key: value; - they're read with a dot,
cat.name, or with square brackets,cat["name"]; - brackets are needed when the key's name is in a variable:
cat[key]; - a new property appears by simply assigning it:
cat.fish = "tuna".
const cat = { name: "Byte" };
cat.fish = "tuna";
const field = "fish";
console.log(cat[field]);
console.log(cat.weight);undefined.Properties can be changed and deleted. delete cat.fleas removes the property entirely — after that it isn't even in Object.keys.
const cat = { name: "Byte", age: 3, fleas: true };
cat.age = 4; // birthday
delete cat.fleas; // cured
console.log(cat);
// cat = { name: "Someone else" }; — this is not allowed: constconst changes just fine. You only can't put a different object in the variable.Useful tools:
"name" in cat— whether the property exists;Object.keys(cat)— an array of all the keys,Object.values(cat)— of the values;cat.owner?.phone— safe reading: if there's noowner, you get undefined, not an error.
const cat = { name: "Byte", age: 3 };
console.log("age" in cat);
console.log(Object.keys(cat));
console.log(cat.owner?.phone);Object.keys comes in handy for walking over every field when you don't know in advance what they are. On each step the key is in a variable — so the value has to be read with brackets.
const passport = { name: "Byte", age: 3, color: "grey" };
for (const key of Object.keys(passport)) {
console.log(key + ": " + passport[key]);
}passport.key would return undefined three times in a row here.Objects nest inside each other: an order has a customer, a customer has an address. A real story: the server sends an order whose customer hasn't entered an address yet. The code order.customer.address.city crashes with "Cannot read properties of undefined", and the order page goes blank. ?. stops the chain at the first empty link.
const order = { id: 7, customer: { name: "Mittens" } };
console.log(order.customer.name);
console.log(order.customer.address?.city);
console.log(order.courier?.phone);undefined.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.