Cityscape
Girl

JavaScript

Objects: Grouping Data with Key–Value Pairs

Easy
10 min

What Is an Object?

An object is a collection of properties. Each property has a key (or name) and a value. Objects allow you to group related data together.

For example:

let person = {
  name: "Alice",
  age: 25,
  city: "Wonderland"
};

In this example:

  • The variable person holds an object.
  • The object has properties with keys name, age, and city.
  • Each key is connected to a value (for instance, name is connected to "Alice").

Accessing Object Properties

You can read the value of a property using dot notation or bracket notation. For example:

console.log(person.name);     // prints "Alice"
console.log(person["age"]);   // prints 25

Updating Object Properties

You can update a property by using dot notation (or bracket notation) on the object. For example:

person.city = "New Wonderland";
console.log(person.city);  // prints "New Wonderland"

Adding and Removing Object Properties

Adding

To add a new property, simply assign a value to a new key.

person.occupation = "Adventurer";
console.log(person.occupation);  // prints "Adventurer"

Removing

To remove a property, use the delete operator.

delete person.age;
console.log(person.age);  // prints undefined

Exercises

Creating and Printing an Object

  • Create a variable named person using let.
  • Assign it an object with the keys: name (value: "Alice"), age (value: 25), and city (value: "Wonderland").
  • Print the entire object using console.log(person).

Accessing and Updating Object Properties

  • Create a variable named car using let.
  • Assign it an object with the properties: make (value: "Toyota"), model (value: "Camry"), and year (value: 2010).
  • Update the year property to 2020.
  • Print the updated year using console.log(car.year).

Adding and Removing Object Properties

  • Create a variable named book using let.
  • Assign it an object with the properties: title (value: "1984") and author (value: "George Orwell").
  • Add a new property pages with the value 328.
  • Then remove the property author from the object.
  • Print the final object using console.log(book).

hakatemia pro

Ready to become an ethical hacker?
Start today.

As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.