This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Javascript Objects (key-value pairs, accessing properties, nested objects)

JavaScript objects are a fundamental data structure consisting of key-value pairs.

1. Creating JavaScript Objects

An object can be created using curly braces {} with keys (properties) and values:

1const person = {
2 name: "Amir",
3 age: 30,
4 isDeveloper: true
5};
6

2. Accessing Properties

You can access properties in two ways:

  • Dot Notation: object.property

  • Bracket Notation: object["property"]

1console.log(person.name); // Output: "Amir"
2console.log(person["age"]); // Output: 30
3

3. Adding and Modifying Properties

You can add or modify properties using dot or bracket notation.

1person.city = "Tehran";
2person["country"] = "Iran";
3console.log(person);
4// { name: 'Amir', age: 30, isDeveloper: true, city: 'Tehran', country: 'Iran' }
5

4. Deleting Properties

Use the delete keyword to remove properties.

1delete person.isDeveloper;
2console.log(person);
3// { name: 'Amir', age: 30, city: 'Tehran', country: 'Iran' }
4

5. Nested Objects

Objects can contain other objects as values, creating a nested structure.

1const user = {
2 id: 1,
3 name: "Amir",
4 address: {
5 street: "123 Main St",
6 city: "Tehran",
7 country: "Iran"
8 }
9};
10

Accessing Nested Properties

To access nested properties, chain the dot or bracket notation.

1console.log(user.address.city); // Output: "Tehran"
2console.log(user["address"]["country"]); // Output: "Iran"
3

Modifying Nested Properties

You can also modify nested properties similarly.

1user.address.street = "456 Elm St";
2console.log(user.address.street); // Output: "456 Elm St"
3

Optional Chaining

For deeply nested properties, optional chaining (?.) is helpful if some properties might be undefined.

1console.log(user.address?.zipCode); // Output: undefined, without error

6. Looping Through Properties

To loop through an object’s properties, use for...in or Object.keys().

1for (let key in user) {
2 console.log(key, user[key]);
3}
4

Or using Object.entries() for both keys and values:

1Object.entries(user).forEach(([key, value]) => {
2 console.log(key, value);
3});

7. Checking Property Existence

Use the in operator or hasOwnProperty().

1console.log("name" in person); // true
2console.log(person.hasOwnProperty("age")); // true

Mastering these techniques allows for more complex manipulations, especially useful in frameworks like React and data-driven applications.