Objects in JavaScript
Objects are one of the most fundamental data structures in JavaScript. They allow you to store collections of key-value pairs and represent real-world entities in your code.
π What is an Object?
An object is a collection of related data and/or functionality, stored as key-value pairs called properties. When a property holds a function, itβs called a method.
const person = { name: "Alice", age: 25, greet: function() { console.log("Hello!"); }};π₯ Creating Objects
1. Object Literal (Most Common)
const car = { brand: "Toyota", model: "Camry", year: 2023};2. Using new Object()
const book = new Object();book.title = "JavaScript Guide";book.author = "John Doe";3. Using Constructor Function
function Person(name, age) { this.name = name; this.age = age;}
const user = new Person("Bob", 30);4. Using Object.create()
const prototypeObj = { greet() { console.log(`Hello, ${this.name}`); }};
const newObj = Object.create(prototypeObj);newObj.name = "Charlie";newObj.greet(); // Hello, Charlieπ Accessing Properties
Dot Notation
const user = { name: "Alice", age: 25 };console.log(user.name); // AliceBracket Notation
console.log(user["age"]); // 25
// Useful for dynamic keysconst key = "name";console.log(user[key]); // AliceβοΈ Adding, Modifying, and Deleting Properties
const obj = { a: 1 };
// Addobj.b = 2;
// Modifyobj.a = 10;
// Deletedelete obj.b;
console.log(obj); // { a: 10 }π Checking Properties
in Operator
const car = { brand: "Honda" };console.log("brand" in car); // trueconsole.log("model" in car); // falsehasOwnProperty()
console.log(car.hasOwnProperty("brand")); // trueπ Looping Through Objects
for...in Loop
const user = { name: "Alice", age: 25, city: "NYC" };
for (let key in user) { console.log(`${key}: ${user[key]}`);}Object.keys(), Object.values(), Object.entries()
const product = { name: "Laptop", price: 999 };
Object.keys(product); // ["name", "price"]Object.values(product); // ["Laptop", 999]Object.entries(product); // [["name", "Laptop"], ["price", 999]]π οΈ Useful Object Methods
Object.assign()
Copies properties from one or more source objects to a target object.
const target = { a: 1 };const source = { b: 2, c: 3 };const result = Object.assign(target, source);console.log(result); // { a: 1, b: 2, c: 3 }Object.freeze()
Makes an object immutable (cannot add, modify, or delete properties).
const config = { apiKey: "12345" };Object.freeze(config);config.apiKey = "67890"; // No effectconsole.log(config.apiKey); // "12345"Object.seal()
Prevents adding or deleting properties but allows modification.
const settings = { theme: "dark" };Object.seal(settings);settings.theme = "light"; // Workssettings.fontSize = 14; // Ignoreddelete settings.theme; // IgnoredObject.isFrozen() and Object.isSealed()
Object.isFrozen(config); // trueObject.isSealed(settings); // trueπ― Object Destructuring
Extract properties into variables easily.
const user = { name: "Alice", age: 25, city: "NYC" };
const { name, age } = user;console.log(name); // Aliceconsole.log(age); // 25
// With default valuesconst { country = "USA" } = user;console.log(country); // USA
// Renamingconst { name: userName } = user;console.log(userName); // Aliceπ¦ Nested Objects
Objects can contain other objects.
const company = { name: "TechCorp", address: { city: "San Francisco", zip: "94102" }};
console.log(company.address.city); // San Francisco
// Destructuring nested objectsconst { address: { city } } = company;console.log(city); // San Franciscoπ Object Shorthand (ES6+)
Property Shorthand
const name = "Alice";const age = 25;
// Instead of { name: name, age: age }const user = { name, age };Method Shorthand
const calculator = { add(a, b) { return a + b; }, subtract(a, b) { return a - b; }};Computed Property Names
const key = "dynamicKey";const obj = { [key]: "value", [`${key}_2`]: "another value"};console.log(obj.dynamicKey); // "value"π Copying Objects
Shallow Copy
const original = { a: 1, b: { c: 2 } };
// Using spread operatorconst copy1 = { ...original };
// Using Object.assign()const copy2 = Object.assign({}, original);
// Note: Nested objects are still referenced!copy1.b.c = 99;console.log(original.b.c); // 99 (affected!)Deep Copy
// Using JSON (simple but has limitations)const deepCopy = JSON.parse(JSON.stringify(original));
// Using structuredClone (modern browsers)const deepCopy2 = structuredClone(original);β οΈ Common Pitfalls
- Reference vs Value: Objects are passed by reference, not by value.
const obj1 = { a: 1 };const obj2 = obj1;obj2.a = 100;console.log(obj1.a); // 100 (both point to same object)- Comparing Objects:
===compares references, not content.
const a = { x: 1 };const b = { x: 1 };console.log(a === b); // false (different references)typeof null: Returns"object"(historical bug).
typeof null; // "object"β Best Practices
- Use object literals for simple objects
- Use destructuring for cleaner code
- Use
constfor objects that shouldnβt be reassigned - Use
Object.freeze()for truly immutable objects - Be careful with shallow copies when dealing with nested objects
- Use
Object.keys(),Object.values(), orObject.entries()for iteration
π Resources
Happy Coding!