Objects in JavaScript Overview
In JavaScript, objects are one of the core building blocks of the language. They allow developers to group related data and functionality into a single, structured entity. Whether you’re managing user data, API responses, or configurations, understanding objects is essential to mastering JavaScript.
What is an Object in JavaScript?
An object is a collection of properties, where each property is a key–value pair.
Objects are mutable, meaning their properties can be added, changed, or deleted after creation. Objects are used to represent real-world entities such as users, products, or cars, and they help organize data efficiently.
Creating Objects in JavaScript
There are several ways to create objects in JavaScript:
a. Object Literal
The simplest and most common method.
const person = {
name: "Alice",
age: 25,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
b. Using the Object Constructor
const person = new Object();
person.name = "Alice";
person.age = 25;
c. Using a Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = new Person("Alice", 25);
d. Using Object.create()
Creates a new object with a specific prototype.
const proto = { greet: function() { console.log("Hello!"); } };
const obj = Object.create(proto);
obj.name = "Alice";
e. Using ES6 Classes
Modern, syntactic sugar over constructor functions.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const alice = new Person("Alice", 25);
Working with Object Properties
Accessing Properties
- Dot notation:
person.name
- Bracket notation:
person["name"]
Adding or Modifying Properties
person.job = "Developer"; // Add
person.age = 26; // Modify
Deleting Properties
delete person.age;
Computed Property Names (ES6+)
const key = "name";
const obj = { [key]: "Alice" }; // { name: "Alice" }
Object Methods
Methods are functions stored as properties in an object.
const person = {
name: "Alice",
greet() {
console.log(`Hi, I'm ${this.name}`);
}
};
person.greet(); // Hi, I'm Alice
Prototypes and Inheritance
JavaScript uses prototypal inheritance — every object inherits from another object called its prototype.
const person = { name: "Alice" };
const employee = Object.create(person);
employee.job = "Developer";
console.log(employee.name); // Inherited from person
Common Object Methods
Method | Description |
---|---|
Object.keys(obj) | Returns an array of property names. |
Object.values(obj) | Returns an array of property values. |
Object.entries(obj) | Returns key–value pairs as arrays. |
Object.assign(target, ...sources) | Copies properties to target. |
Object.freeze(obj) | Prevents all modifications. |
Object.seal(obj) | Prevents adding/removing properties. |
Object.hasOwn(obj, key) | Checks if key is a direct property (ES2022). |
Iterating Over Objects
Using for...in Loop
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Using Object.entries() with for...of
for (let [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
Object Destructuring (ES6+)
Extract properties directly into variables.
const { name, age } = person;
console.log(name, age); // Alice, 25
JSON and Objects
Convert between JavaScript objects and JSON strings.
const json = JSON.stringify(person); // Object → JSON
const obj = JSON.parse(json); // JSON → Object
Key Characteristics of JavaScript Objects
- Dynamic: You can add or remove properties at runtime.
- Reference Type: Objects are assigned by reference, not copied.
const obj1 = { a: 1 };
const obj2 = obj1;
obj2.a = 2;
console.log(obj1.a); // 2
Equality: Two objects are equal only if they reference the same instance.
console.log({ a: 1 } === { a: 1 }); // false
Common Use Cases
- Representing structured data (e.g., user profiles)
- Storing configurations or settings
- Creating reusable components and modules
- Implementing prototypes and inheritance
- Quick key-value storage and lookups
Advanced Object Features
Symbols
Unique keys that prevent naming conflicts.
const id = Symbol("id");
const user = { [id]: 123 };
Getters and Setters
Define how properties are accessed or modified.
const obj = {
get name() { return this._name; },
set name(value) { this._name = value; }
}
Proxies
Intercept and customize object behavior.
const handler = {
get(target, prop) {
return prop in target ? target[prop] : "Not Found";
}
};
const proxy = new Proxy({ name: "Alice" }, handler);
console.log(proxy.age); // Not Found