What are Object in JavaScript
•20 min read

An object is a collection of key-value pairs (properties and methods) that represent a real-world entity. Objects are one of the fundamental data types in JavaScript and are used to store and organize related data and functionality.
Creating Objects
1. Object Literal (Most Common)
javascript
const person = {
name: "Alice",
age: 30,
city: "New York",
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
console.log(person.name); // Alice
console.log(person["age"]); // 30
person.greet(); // Hello, I'm Alice JavaScript2. Constructor Function
javascript
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.drive = function() {
return this.make + " " + this.model + " is driving";
};
}
const myCar = new Car("Toyota", "Corolla", 2022);
console.log(myCar.make); // Toyota
console.log(myCar.drive()); // Toyota Corolla is driving JavaScript3. Object.create()
javascript
const vehiclePrototype = {
start() {
return "Engine started";
}
};
const bike = Object.create(vehiclePrototype);
bike.type = "motorcycle";
console.log(bike.start()); // Engine startedJavaScriptAccessing Properties
javascript
const book = { title: "JavaScript", pages: 500 };
// Dot notation
console.log(book.title); // JavaScript
// Bracket notation
console.log(book["pages"]); // 500 JavaScriptAdding & Modifying Properties
javascript
const laptop = { brand: "Dell" };
// Add new property
laptop.price = 1000;
laptop["ram"] = "16GB";
// Modify existing
laptop.brand = "HP";
console.log(laptop); // { brand: 'HP', price: 1000, ram: '16GB' } JavaScriptDeleting Properties
javascript
const item = { name: "pen", color: "blue" };
delete item.color;
console.log(item); // { name: 'pen' }JavaScriptUseful Object Methods
javascript
const student = { name: "Bob", grade: "A", subject: "Math" };
// Get all keys
console.log(Object.keys(student)); // ['name', 'grade', 'subject']
// Get all values
console.log(Object.values(student)); // ['Bob', 'A', 'Math']
// Get key-value pairs
console.log(Object.entries(student)); // [['name','Bob'], ['grade','A'], ['subject','Math']]
// Check if property exists
console.log("name" in student); // true JavaScriptObjects are incredibly flexible and powerful in JavaScript—they're the foundation for organizing code and data!


