Objects

In JavaScript, objects are collections of related data and functionality. They store data in key-value pairs, where keys are strings (or symbols) and values can be any data type, including other objects or functions.

Illustration of objects
Illustration of objects

💡 What is an Object?

An object groups properties and methods to represent real-world entities or abstract data structures.

Creating Objects

  • Object literal syntax: The most common and concise way.
  • Using new Object(): Less common, more verbose.

📌 Deep Dive: Object Literal Example

JAVASCRIPT
const person = {
  name: "Alice",
  age: 30,
  greet: function() {
    return "Hello, " + this.name + "!";
  }
};

console.log(person.name);    // Alice
console.log(person.greet()); // Hello, Alice!
Output
Alice
Hello, Alice!

Accessing and Modifying Properties

Properties can be accessed or changed using:

  • object.propertyName
  • object["propertyName"] (useful with dynamic or special keys)

📌 Deep Dive: Access & Modification

JAVASCRIPT
const car = {
  brand: "Toyota",
  year: 2021
};

// Access
console.log(car.brand);      // Toyota
console.log(car["year"]);    // 2021

// Modify
car.year = 2022;
car["color"] = "red";

console.log(car.year);       // 2022
console.log(car.color);      // red
Output
Toyota
2021
2022
red

💡 Dynamic Property Access

Bracket notation allows accessing properties with keys stored in variables or with keys that include spaces or special characters.

Objects vs. Arrays

Objects Compared to Arrays
ObjectsArrays
Store data as key-value pairsStore ordered data as indexed elements
Keys are usually stringsIndices are numeric and ordered
Used for representing entities or recordsUsed for lists or collections
Access properties via keysAccess elements via indices

Methods in Objects

Functions inside objects are called methods. They can use this to refer to the current object.

📌 Deep Dive: Methods Using this

JAVASCRIPT
const rectangle = {
  width: 10,
  height: 5,
  area: function() {
    return this.width * this.height;
  }
};

console.log(rectangle.area()); // 50
Output
50

Common Object Methods

  • Object.keys(obj) - Returns an array of keys
  • Object.values(obj) - Returns an array of values
  • Object.entries(obj) - Returns an array of [key, value] pairs

📌 Deep Dive: Object Utility Methods

JAVASCRIPT
const user = {
  id: 101,
  username: "jsmith",
  active: true
};

console.log(Object.keys(user));   // ["id", "username", "active"]
console.log(Object.values(user)); // [101, "jsmith", true]
console.log(Object.entries(user)); // [["id", 101], ["username", "jsmith"], ["active", true]]
Output
["id", "username", "active"]
[101, "jsmith", true]
[["id", 101], ["username", "jsmith"], ["active", true]]

⚠️ Objects are reference types

Assigning or passing objects copies the reference, not the actual object. Changes affect all references.