JavaScript Object Definition
14 April 2025 | Category: JavaScript
In JavaScript, an object is a complex data type used to store key-value pairs. These key-value pairs are also known as properties and can hold any value—like strings, numbers, arrays, or even functions (called methods when inside objects).
Objects help organize related data and functionalities in a structured way.
🗂️ Object Syntax
const person = {
name: "John",
age: 30,
isEmployed: true,
greet: function () {
console.log("Hello!");
}
};
name
,age
, andisEmployed
are propertiesgreet
is a method (a function inside an object)
đź§ľ Accessing Object Properties
🔹 Dot Notation
console.log(person.name); // Output: John
🔹 Bracket Notation
console.log(person["age"]); // Output: 30
Bracket notation is useful when property names are stored in a variable or contain spaces.
🛠️ Modifying Object Properties
person.age = 31;
person["name"] = "Jane";
You can add new properties too:
person.city = "New York";
🗑️ Deleting Properties
delete person.isEmployed;
âś… Checking if a Property Exists
console.log("age" in person); // true
console.log(person.hasOwnProperty("city")); // true
📦 Creating Objects Dynamically
Using Object Constructor
const car = new Object();
car.brand = "Toyota";
car.year = 2022;
Using Factory Function
function createUser(name, email) {
return {
name,
email,
isLoggedIn: false
};
}
🧬 Nested Objects
const user = {
name: "Alice",
address: {
street: "123 Main St",
city: "Mumbai"
}
};
console.log(user.address.city); // Mumbai
🔄 Looping Through an Object
for (let key in person) {
console.log(key + ": " + person[key]);
}
đź§ Why Use Objects?
- To group related data and behavior (methods)
- To build complex data structures (e.g., user profiles, settings)
- They’re the foundation of many concepts in JavaScript like classes, APIs, and JSON