Skip to content
blog
2 min read

Object

JavaScript objects store key-value pairs. Learn to access properties with dot and bracket notation, set and delete values, and use functions as methods.

An object groups related data together as key-value pairs. Think of it as a container with labeled slots.

Creating an Object

const person = {
name: "Reza",
age: 28,
city: "Jakarta",
};

Keys are strings (or symbols). Values can be anything.

Accessing Properties

Dot notation — the clean way when you know the key name:

person.name; // 'Reza'
person.age; // 28

Bracket notation — required when the key is dynamic or has special characters:

person["name"]; // 'Reza'
const key = "city";
person[key]; // 'Jakarta'
person["my-key"]; // works — dot notation can't handle hyphens

Setting and Updating Values

person.email = "reza@example.com"; // add new property
person.age = 29; // update existing

Deleting a Property

delete person.city;

Methods

A method is a function stored as an object property:

const person = {
name: "Reza",
greet() {
console.log(`Hi, I'm ${this.name}`);
},
};
person.greet(); // Hi, I'm Reza

this inside a method refers to the object the method belongs to.

Checking if a Property Exists

"name" in person; // true
person.hasOwnProperty("email"); // false

Looping Over Properties

for (const key in person) {
console.log(`${key}: ${person[key]}`);
}

Or get all keys as an array:

Object.keys(person); // ['name', 'age']
Object.values(person); // ['Reza', 28]
Object.entries(person); // [['name', 'Reza'], ['age', 28]]