~/hackweb.dev
JavaScript Objects Basics
Quiz
...

JavaScript Objects Basics

beginner · updated Tue Sep 08 2026Contribute

Learn to create, access, and manipulate objects.

JavaScript Objects Basics

Objects are collections of key-value pairs that store related data.

What Are Objects?

// Without objects
let name = "John";
let age = 25;

// With objects — organized
let person = { name: "John", age: 25 };

Creating Objects

let person = { name: "John", age: 25, city: "NYC" };
let empty = {};

Accessing Properties

let person = { name: "John", age: 25 };

person.name;     // dot notation — "John"
person["age"];   // bracket notation — 25

Tip: Use dot notation for static keys. Use bracket notation when the key is dynamic.

Adding and Modifying

let person = { name: "John" };

person.age = 25;     // add
person.name = "Jane"; // modify

Deleting Properties

let person = { name: "John", age: 25 };
delete person.age;
console.log(person); // { name: "John" }

Checking Properties

let person = { name: "John", age: 25 };

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

Iterating Over Objects

let person = { name: "John", age: 25 };

Object.keys(person);    // ["name", "age"]
Object.values(person);  // ["John", 25]
Object.entries(person); // [["name", "John"], ["age", 25]]

for (let [key, val] of Object.entries(person)) {
  console.log(`${key}: ${val}`);
}

Nested Objects

let person = {
  name: "John",
  address: { street: "123 Main St", city: "NYC" },
  hobbies: ["reading", "gaming"]
};

person.address.city; // "NYC"

Remember: Keep nesting shallow — deep structures are hard to maintain.

Complete Example: User Profile

let userProfile = {
  username: "john_doe",
  age: 25,
  address: { city: "NYC", state: "NY" },
  settings: { theme: "dark", notifications: true }
};

console.log(`City: ${userProfile.address.city}`);     // "NYC"
console.log(`Theme: ${userProfile.settings.theme}`);   // "dark"

Best Practices

  1. Use descriptive keys — meaningful property names
  2. Use const — if the object won’t be reassigned
  3. Keep it flat — avoid deep nesting
  4. Validate data — check for required properties

Common Mistakes

  1. Forgetting quotes on keys — keys with spaces need quotes
  2. Accessing non-existent properties — returns undefined
  3. Modifying const objects — you can change properties, just not reassign
  4. Using for...in on arrays — use for...of instead