Skip to main content
๐Ÿ“ฆbeginner

Object Basics

Objects are key-value stores and the foundation of JavaScript's data model. Learn to create, access, modify, and work with objects.

What is an Object?

An object is a collection of key-value pairs (also called properties). Keys are strings (or symbols), and values can be anything.

hljs javascript
const person = {
  name: "Alice",         // string value
  age: 30,               // number value
  isActive: true,        // boolean value
  scores: [95, 88, 92],  // array value
  address: {             // nested object
    city: "New York",
    zip: "10001",
  },
  greet() {              // method (function as value)
    return `Hi, I'm ${this.name}`;
  },
};

Accessing Properties

hljs javascript
const car = { make: "Toyota", model: "Camry", year: 2023 };

// Dot notation (preferred when key is a valid identifier)
console.log(car.make);   // "Toyota"
console.log(car.year);   // 2023

// Bracket notation (required for dynamic keys or special characters)
console.log(car["model"]);  // "Camry"

const key = "year";
console.log(car[key]);   // 2023 โ€” dynamic access

// Non-existent property
console.log(car.color); // undefined (no error)

Modifying Objects

hljs javascript
const user = { name: "Bob", age: 25 };

// Update a property
user.age = 26;

// Add a new property
user.email = "bob@example.com";

// Delete a property
delete user.age;

console.log(user); // { name: "Bob", email: "bob@example.com" }

Destructuring

Extract properties into variables cleanly:

hljs javascript
const { name, age, city = "Unknown" } = person;
console.log(name);  // "Alice"
console.log(age);   // 30
console.log(city);  // "Unknown" (default value)

// Rename during destructuring
const { name: fullName } = person;
console.log(fullName); // "Alice"

// Nested destructuring
const { address: { city: personCity } } = person;
console.log(personCity); // "New York"

// In function parameters
function displayUser({ name, age }) {
  console.log(`${name}, age ${age}`);
}
displayUser(person);

Spread and Rest with Objects

hljs javascript
const defaults = { color: "blue", size: "medium", weight: 10 };
const customized = { ...defaults, color: "red", extra: "bonus" };
console.log(customized);
// { color: "red", size: "medium", weight: 10, extra: "bonus" }
// Later properties override earlier ones

// Copy an object (shallow)
const copy = { ...person };

// Rest in destructuring
const { name: n, age: a, ...rest } = person;
console.log(rest); // everything except name and age

Object Methods

hljs javascript
const rectangle = {
  width: 10,
  height: 5,
  area() {
    return this.width * this.height;
  },
  perimeter() {
    return 2 * (this.width + this.height);
  },
};

console.log(rectangle.area());      // 50
console.log(rectangle.perimeter()); // 30

Useful Object Methods

hljs javascript
const obj = { a: 1, b: 2, c: 3 };

// Keys, values, entries
Object.keys(obj);    // ["a", "b", "c"]
Object.values(obj);  // [1, 2, 3]
Object.entries(obj); // [["a",1], ["b",2], ["c",3]]

// Iterate entries
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

// Merge objects
const merged = Object.assign({}, obj, { d: 4 });
// or using spread: { ...obj, d: 4 }

// Freeze (make immutable)
const frozen = Object.freeze({ x: 1 });
frozen.x = 99; // silently fails (or throws in strict mode)
console.log(frozen.x); // 1

// Check if property exists
"a" in obj;           // true
obj.hasOwnProperty("a"); // true

Computed Property Names

hljs javascript
const prefix = "get";
const field = "Name";

const obj = {
  [`${prefix}${field}`]: "Alice", // computed key
  ["key-" + 1]: "value",
};

console.log(obj.getName);  // "Alice"
console.log(obj["key-1"]); // "value"

Shorthand Properties and Methods

hljs javascript
const name = "Alice";
const age = 30;

// Old way
const user1 = { name: name, age: age };

// Shorthand (ES6)
const user2 = { name, age };
console.log(user2); // { name: "Alice", age: 30 }

// Method shorthand
const calculator = {
  add(a, b) { return a + b; },       // shorthand
  sub: function(a, b) { return a - b; }, // old way
};
โ–ถTry it yourself

Key Takeaways

  • Objects store key-value pairs; keys are usually strings
  • Use dot notation normally; bracket notation for dynamic keys
  • Destructuring extracts properties into variables cleanly
  • ...spread copies and merges objects (shallow copy)
  • Object.keys(), Object.values(), Object.entries() for iteration
  • Methods are functions stored as object properties

Ready to test your knowledge?

Take a quiz on what you just learned.

Take the Quiz โ†’