Objects
Programming Languages · JavaScript Objects · 14 min
Group related values under named keys, give them methods, and loop over them.
Making an object
An object groups related values under names called keys. Write it in curly braces as key: value pairs, separated by commas. Read a value with a dot.
const dog = { name: "Rex", age: 3 };
console.log(dog.name); // Rex
Create a
constobjectbookwithtitleset to"Dune"andpagesset to412.Print
book.title.
Dots and brackets
There are two ways to read a key. Dot: car.brand. Brackets with a string: car["brand"].
Brackets shine when the key is stored in a variable:
const pick = "brand";
console.log(car[pick]); // same as car.brand
car.pick would look for a key literally called pick.
Print
car.brandusing a dot.Print the value for the key stored in
key, using brackets.
Adding and updating keys
Set a key with =. If the key exists, its value is updated. If it doesn't, it's added.
const cat = { name: "Tom" };
cat.name = "Tim"; // update
cat.age = 4; // add
Update
player.levelto2.Add a new key
coinsset to50.Print
Mia is level 2 with 50 coinsusing a template literal and the player's keys.
Methods: functions inside objects
A function stored in an object is called a method. Inside it, this means "the object I belong to", so this.name reads the object's own name.
const cat = {
name: "Tom",
meow() {
console.log(`${this.name} says meow`);
},
};
cat.meow(); // Tom says meow
Add a method
greet()torobotthat printsBeep! I amand its name, usingthis.name.Below the object, call
robot.greet().
Looping over an object
for...in walks through an object's keys. Use brackets to get each value:
for (const key in pet) {
console.log(key, pet[key]);
}
Object.entries(obj) gives you [key, value] pairs instead, which you can unpack straight away:
for (const [key, value] of Object.entries(pet)) { ... }
Use
for...into print each item asapples: 5,pears: 2and so on.Then use
Object.entriesto print each one the other way round:5 apples,2 pears,9 plums.
Put it together: a contact card
Update a contact, then print every detail with a loop. New keys go at the end, so the loop prints them last.
Add a key
ageset to30.Change
cityto"Milan".Loop over
contactand print each pair askey = value.
More in JavaScript Objects
Previous: Array Methods · Next: Classes