JavaScript Mastery - Objects

Code SubtleCode Subtle
13 min read

Introduction to Objects

Objects in JavaScript are reference types that store data as key-value pairs. Unlike arrays which use numeric indices, objects use named keys to access values. Objects are fundamental to JavaScript and represent real-world entities with properties and behaviors. They are mutable and can contain any data type including other objects, arrays, and functions.

Syntax:

const objectName = {
  key1: value1,
  key2: value2,
  key3: value3
};

Examples:

Example 1: Basic Person Object

const person = {
  name: "John Doe",
  age: 30,
  city: "New York"
};
console.log(person); // { name: "John Doe", age: 30, city: "New York" }

Example 2: Product Object

const product = {
  id: 101,
  title: "Laptop",
  price: 999.99,
  inStock: true
};
console.log(product); // { id: 101, title: "Laptop", price: 999.99, inStock: true }

Example 3: Mixed Data Types

const student = {
  name: "Alice",
  grades: [85, 92, 78],
  isActive: true,
  address: null
};
console.log(student); // { name: "Alice", grades: [85, 92, 78], isActive: true, address: null }

Ways to Create Objects

JavaScript provides multiple ways to create objects. The most common methods are object literals, the new keyword with Object constructor, and Object.create() method. Each method has its own use cases and benefits. Object literals are the most straightforward and widely used approach for creating simple objects.

Syntax:

// Object Literal
const obj1 = { key: value };

// Constructor Function
const obj2 = new Object();

// Object.create()
const obj3 = Object.create(null);

Examples:

Example 1: Object Literal

const car = {
  brand: "Toyota",
  model: "Camry",
  year: 2023,
  color: "blue"
};
console.log(car); // { brand: "Toyota", model: "Camry", year: 2023, color: "blue" }

Example 2: Constructor Function

const book = new Object();
book.title = "JavaScript Guide";
book.author = "John Smith";
book.pages = 350;
book.published = true;
console.log(book); // { title: "JavaScript Guide", author: "John Smith", pages: 350, published: true }

Example 3: Object.create() Method

const animal = Object.create(null);
animal.species = "Dog";
animal.breed = "Golden Retriever";
animal.age = 3;
animal.friendly = true;
console.log(animal); // { species: "Dog", breed: "Golden Retriever", age: 3, friendly: true }

Accessing Object Properties

Object properties can be accessed using two main notations: dot notation and bracket notation. Dot notation is more common and readable when you know the property name at compile time. Bracket notation is useful when property names are dynamic, contain special characters, or are stored in variables. Both methods allow you to retrieve values from object properties.

Syntax:

// Dot Notation
objectName.propertyName

// Bracket Notation
objectName["propertyName"]
objectName[variableName]

Examples:

Example 1: Dot Notation

const employee = {
  firstName: "Sarah",
  lastName: "Johnson",
  position: "Manager",
  salary: 75000
};
console.log(employee.firstName); // "Sarah"
console.log(employee.position); // "Manager"
console.log(employee.salary); // 75000

Example 2: Bracket Notation

const user = {
  username: "john_doe",
  email: "john@example.com",
  "full-name": "John Doe",
  age: 28
};
console.log(user["username"]); // "john_doe"
console.log(user["full-name"]); // "John Doe"
console.log(user["age"]); // 28

Example 3: Dynamic Property Access

const settings = {
  theme: "dark",
  language: "english",
  notifications: true
};
const propertyName = "theme";
console.log(settings[propertyName]); // "dark"

const keys = ["language", "notifications"];
keys.forEach(key => console.log(settings[key])); // "english", true

Adding and Updating Properties

Object properties can be added or updated after the object is created using either dot notation or bracket notation. When you assign a value to a property that doesn't exist, it gets added to the object. If the property already exists, its value gets updated. This dynamic nature makes objects very flexible for storing and modifying data.

Syntax:

// Adding/Updating with Dot Notation
objectName.newProperty = value;

// Adding/Updating with Bracket Notation
objectName["newProperty"] = value;

Examples:

Example 1: Adding New Properties

const smartphone = {
  brand: "Apple",
  model: "iPhone 14"
};
smartphone.storage = "128GB";
smartphone.color = "blue";
smartphone["price"] = 799;
console.log(smartphone); // { brand: "Apple", model: "iPhone 14", storage: "128GB", color: "blue", price: 799 }

Example 2: Updating Existing Properties

const profile = {
  name: "Mike Wilson",
  age: 32,
  city: "Boston"
};
profile.age = 33; // Birthday update
profile.city = "Seattle"; // Moved to new city
profile["name"] = "Michael Wilson"; // Full name update
console.log(profile); // { name: "Michael Wilson", age: 33, city: "Seattle" }

Example 3: Dynamic Property Addition

const inventory = {
  apples: 50,
  bananas: 30
};
const newFruit = "oranges";
const quantity = 25;
inventory[newFruit] = quantity;
inventory["grapes"] = 40;
console.log(inventory); // { apples: 50, bananas: 30, oranges: 25, grapes: 40 }

Deleting Properties

The delete operator is used to remove properties from objects. It returns true if the property is successfully deleted or if the property doesn't exist. The delete operation modifies the original object by completely removing the specified property. It's important to note that delete only works on object properties, not on variables or function parameters.

Syntax:

delete objectName.propertyName;
delete objectName["propertyName"];

Examples:

Example 1: Deleting with Dot Notation

const laptop = {
  brand: "Dell",
  processor: "Intel i7",
  ram: "16GB",
  storage: "512GB SSD",
  price: 1299
};
delete laptop.price;
delete laptop.storage;
console.log(laptop); // { brand: "Dell", processor: "Intel i7", ram: "16GB" }

Example 2: Deleting with Bracket Notation

const restaurant = {
  name: "Pizza Palace",
  cuisine: "Italian",
  rating: 4.5,
  "delivery-time": "30 minutes",
  location: "Downtown"
};
delete restaurant["delivery-time"];
delete restaurant["location"];
console.log(restaurant); // { name: "Pizza Palace", cuisine: "Italian", rating: 4.5 }

Example 3: Conditional Property Deletion

const gameCharacter = {
  name: "Hero",
  level: 15,
  health: 100,
  mana: 50,
  temporaryBoost: true
};
if (gameCharacter.temporaryBoost) {
  delete gameCharacter.temporaryBoost;
}
delete gameCharacter.mana;
console.log(gameCharacter); // { name: "Hero", level: 15, health: 100 }

Nested Objects

Nested objects are objects that contain other objects as property values. This creates a hierarchical structure that can represent complex data relationships. Nested objects are commonly used to model real-world entities with multiple levels of information. You can access nested properties by chaining dot notation or bracket notation.

Syntax:

const nestedObject = {
  level1: {
    level2: {
      level3: value
    }
  }
};
// Access: nestedObject.level1.level2.level3

Examples:

Example 1: User Profile with Address

const userProfile = {
  personal: {
    firstName: "Emma",
    lastName: "Davis",
    age: 28
  },
  address: {
    street: "123 Main St",
    city: "Portland",
    zipCode: "97201"
  },
  preferences: {
    theme: "dark",
    language: "english"
  }
};
console.log(userProfile.personal.firstName); // "Emma"
console.log(userProfile.address.city); // "Portland"
console.log(userProfile.preferences.theme); // "dark"

Example 2: Company Structure

const company = {
  name: "Tech Solutions Inc",
  departments: {
    engineering: {
      employees: 25,
      manager: "John Smith"
    },
    sales: {
      employees: 15,
      manager: "Sarah Johnson"
    },
    hr: {
      employees: 5,
      manager: "Mike Wilson"
    }
  }
};
console.log(company.departments.engineering.manager); // "John Smith"
console.log(company.departments.sales.employees); // 15

Example 3: Product Catalog

const product = {
  id: 12345,
  details: {
    name: "Wireless Headphones",
    specifications: {
      battery: "20 hours",
      connectivity: "Bluetooth 5.0",
      weight: "250g"
    },
    pricing: {
      retail: 199.99,
      wholesale: 149.99
    }
  }
};
console.log(product.details.specifications.battery); // "20 hours"
console.log(product.details.pricing.retail); // 199.99

Object Storage and Reference Types

Objects in JavaScript are reference types, meaning variables store references (memory addresses) to objects rather than the actual object values. When you assign an object to multiple variables, they all point to the same object in memory. This means changes made through one variable affect all other variables referencing the same object. Understanding this concept is crucial for avoiding unexpected behavior in JavaScript applications.

Syntax:

const obj1 = { key: value };
const obj2 = obj1; // obj2 references the same object as obj1

Examples:

Example 1: Reference Sharing

const original = {
  name: "Alice",
  age: 25,
  hobbies: ["reading", "swimming"]
};
const copy = original;
copy.age = 26;
copy.hobbies.push("cycling");
console.log(original.age); // 26 (changed!)
console.log(original.hobbies); // ["reading", "swimming", "cycling"]
console.log(original === copy); // true (same reference)

Example 2: Function Parameter References

function modifyUser(user) {
  user.status = "active";
  user.lastLogin = new Date();
}
const userData = {
  username: "john_doe",
  email: "john@example.com"
};
modifyUser(userData);
console.log(userData); // { username: "john_doe", email: "john@example.com", status: "active", lastLogin: [current date] }

Example 3: Array of Object References

const baseConfig = {
  theme: "light",
  language: "en"
};
const userConfigs = [baseConfig, baseConfig, baseConfig];
userConfigs[0].theme = "dark";
console.log(userConfigs[1].theme); // "dark" (all references affected)
console.log(userConfigs[2].theme); // "dark" (all references affected)

Traversing Object Keys

Traversing or iterating through object properties is essential for processing object data. JavaScript provides several methods including for...in loops, Object.keys(), Object.values(), and Object.entries(). Each method serves different purposes and offers various ways to access object properties, values, or both. The choice depends on what information you need during iteration.

Syntax:

// for...in loop
for (let key in object) { }

// Object.keys()
Object.keys(object).forEach(key => { });

// Object.values()
Object.values(object).forEach(value => { });

// Object.entries()
Object.entries(object).forEach([key, value] => { });

Examples:

Example 1: for...in Loop

const scores = {
  math: 95,
  science: 87,
  english: 92,
  history: 89
};
for (let subject in scores) {
  console.log(`${subject}: ${scores[subject]}`);
}
// Output: math: 95, science: 87, english: 92, history: 89

Example 2: Object.keys() Method

const inventory = {
  laptops: 15,
  mice: 45,
  keyboards: 23,
  monitors: 8
};
const itemNames = Object.keys(inventory);
console.log(itemNames); // ["laptops", "mice", "keyboards", "monitors"]
itemNames.forEach(item => {
  console.log(`We have ${inventory[item]} ${item}`);
});

Example 3: Object.entries() Method

const weather = {
  temperature: 72,
  humidity: 65,
  windSpeed: 12,
  pressure: 1013
};
Object.entries(weather).forEach(([metric, value]) => {
  console.log(`${metric}: ${value}`);
});
// Output: temperature: 72, humidity: 65, windSpeed: 12, pressure: 1013

Arrays as Objects

In JavaScript, arrays are actually a special type of object with numeric indices as keys. This means arrays inherit object properties and methods while having additional array-specific functionality. Understanding this relationship helps explain why arrays can have both numeric indices and named properties. Arrays maintain their length property and array methods while still being objects underneath.

Syntax:

const arr = [1, 2, 3]; // Array with numeric indices
arr.customProperty = "value"; // Adding object property
console.log(typeof arr); // "object"

Examples:

Example 1: Array with Object Properties

const fruits = ["apple", "banana", "orange"];
fruits.origin = "local farm";
fruits.organic = true;
fruits.season = "summer";
console.log(fruits); // ["apple", "banana", "orange", origin: "local farm", organic: true, season: "summer"]
console.log(fruits.length); // 3 (only counts indexed elements)
console.log(fruits.origin); // "local farm"

Example 2: Array Object Key Iteration

const colors = ["red", "green", "blue"];
colors.favorite = "purple";
colors.total = 4;

for (let key in colors) {
  console.log(`${key}: ${colors[key]}`);
}
// Output: 0: red, 1: green, 2: blue, favorite: purple, total: 4

console.log(Object.keys(colors)); // ["0", "1", "2", "favorite", "total"]

Example 3: Array Constructor as Object

const numbers = new Array(3);
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers.description = "sample numbers";
numbers.createdBy = "system";

console.log(numbers instanceof Array); // true
console.log(numbers instanceof Object); // true
console.log(typeof numbers); // "object"
console.log(numbers.description); // "sample numbers"

Computed Properties

Computed properties allow you to dynamically set object property names using expressions enclosed in square brackets. This feature enables you to create object properties whose names are determined at runtime based on variables, function calls, or expressions. Computed properties are particularly useful when building objects programmatically or when property names come from external sources.

Syntax:

const dynamicKey = "propertyName";
const obj = {
  [dynamicKey]: value,
  [expression]: value
};

Examples:

Example 1: Dynamic Property Names

const prefix = "user";
const suffix = "Data";
const userId = 123;

const userObject = {
  [prefix + suffix]: "John Doe",
  [`${prefix}Id`]: userId,
  [`${prefix}Active`]: true
};
console.log(userObject); // { userData: "John Doe", userId: 123, userActive: true }

Example 2: Function-based Property Names

function getPropertyName(type) {
  return `${type}Count`;
}

const statistics = {
  [getPropertyName("visitor")]: 1250,
  [getPropertyName("page")]: 45,
  [getPropertyName("error")]: 3
};
console.log(statistics); // { visitorCount: 1250, pageCount: 45, errorCount: 3 }

Spread Operator in Objects

The spread operator (...) allows you to copy properties from one or more objects into a new object. It creates a shallow copy of object properties and is useful for merging objects, cloning objects, and creating new objects with additional properties. When properties with the same name exist in multiple objects, the last one takes precedence.

Syntax:

const newObject = { ...object1, ...object2, newProperty: value };

Examples:

Example 1: Object Merging

const basicInfo = {
  name: "David",
  age: 30
};
const contactInfo = {
  email: "david@example.com",
  phone: "555-1234"
};
const preferences = {
  theme: "dark",
  notifications: true
};
const completeProfile = { ...basicInfo, ...contactInfo, ...preferences };
console.log(completeProfile); 
// { name: "David", age: 30, email: "david@example.com", phone: "555-1234", theme: "dark", notifications: true }

Example 2: Object Cloning with Modifications

const originalProduct = {
  id: 1,
  name: "Laptop",
  price: 999,
  category: "Electronics"
};
const discountedProduct = {
  ...originalProduct,
  price: 799,
  onSale: true,
  discount: "20% off"
};
console.log(discountedProduct); 
// { id: 1, name: "Laptop", price: 799, category: "Electronics", onSale: true, discount: "20% off" }

Example 3: Overriding Properties

const defaultSettings = {
  volume: 50,
  brightness: 75,
  autoSave: true,
  theme: "light"
};
const userSettings = {
  volume: 80,
  theme: "dark"
};
const finalSettings = { ...defaultSettings, ...userSettings, lastUpdated: new Date() };
console.log(finalSettings); 
// { volume: 80, brightness: 75, autoSave: true, theme: "dark", lastUpdated: [current date] }

Object Destructuring

Object destructuring is a JavaScript feature that allows you to extract properties from objects and assign them to variables in a single statement. It provides a clean and readable way to unpack object properties, set default values, rename variables, and work with nested objects. Destructuring is particularly useful when working with function parameters and API responses.

Syntax:

const { property1, property2, property3 } = object;
const { property: newName, property2 = defaultValue } = object;

Examples:

Example 1: Basic Destructuring

const student = {
  name: "Lisa",
  grade: "A",
  subject: "Mathematics",
  score: 95,
  passed: true
};
const { name, grade, score } = student;
console.log(name); // "Lisa"
console.log(grade); // "A"
console.log(score); // 95

Example 2: Destructuring with Default Values and Renaming

const apiResponse = {
  status: "success",
  data: {
    userId: 456,
    username: "jane_doe"
  },
  timestamp: "2024-01-15"
};
const { 
  status, 
  message = "No message provided", 
  data: responseData,
  timestamp: createdAt 
} = apiResponse;
console.log(status); // "success"
console.log(message); // "No message provided"
console.log(responseData); // { userId: 456, username: "jane_doe" }
console.log(createdAt); // "2024-01-15"

Example 3: Nested Object Destructuring

const order = {
  orderId: "ORD-12345",
  customer: {
    name: "Robert Smith",
    email: "robert@example.com",
    address: {
      street: "456 Oak Ave",
      city: "Chicago",
      zipCode: "60601"
    }
  },
  items: ["laptop", "mouse"]
};
const { 
  orderId, 
  customer: { 
    name: customerName, 
    address: { city, zipCode } 
  } 
} = order;
console.log(orderId); // "ORD-12345"
console.log(customerName); // "Robert Smith"
console.log(city); // "Chicago"
console.log(zipCode); // "60601"

Objects Inside Arrays

Objects inside arrays are extremely common in JavaScript applications, especially when dealing with data from APIs, databases, or user interfaces. This pattern allows you to store collections of related data where each item has multiple properties. You can access, modify, and manipulate these objects using array methods combined with object property access.

Syntax:

const arrayOfObjects = [
  { property1: value1, property2: value2 },
  { property1: value3, property2: value4 },
  { property1: value5, property2: value6 }
];

Examples:

Example 1: Employee Database

const employees = [
  { id: 1, name: "John Smith", department: "Engineering", salary: 85000 },
  { id: 2, name: "Sarah Johnson", department: "Marketing", salary: 72000 },
  { id: 3, name: "Mike Wilson", department: "Sales", salary: 68000 }
];

employees.forEach(employee => {
  console.log(`${employee.name} works in ${employee.department}`);
});
// Output: John Smith works in Engineering, Sarah Johnson works in Marketing, Mike Wilson works in Sales

const engineeringEmployees = employees.filter(emp => emp.department === "Engineering");
console.log(engineeringEmployees); // [{ id: 1, name: "John Smith", department: "Engineering", salary: 85000 }]

Example 2: Product Catalog

const products = [
  { id: 101, name: "Smartphone", price: 699, category: "Electronics", inStock: true },
  { id: 102, name: "Headphones", price: 199, category: "Electronics", inStock: false },
  { id: 103, name: "Book", price: 15, category: "Education", inStock: true }
];

const totalValue = products.reduce((sum, product) => sum + product.price, 0);
console.log(`Total catalog value: $${totalValue}`); // Total catalog value: $913

const availableProducts = products.filter(product => product.inStock);
console.log(availableProducts.length); // 2

Conclusion

JavaScript objects are fundamental building blocks that enable developers to create complex, interactive applications. From basic key-value storage to advanced patterns like object composition and immutability, objects provide the foundation for organizing and manipulating data effectively.

Understanding these concepts thoroughly will significantly improve your JavaScript programming skills and enable you to build more robust, maintainable applications. Objects are not just data containers but powerful tools for modeling real-world entities and creating organized, functional code structures.

18
Subscribe to my newsletter

Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Code Subtle
Code Subtle

At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!