JavaScript Objects
JavaScript objects group related data and behavior under one name. An object is a collection of key-value pairs called properties. When a property holds a function, it is called a method.
Creating Objects and Accessing Properties
Use dot notation for fixed names and bracket notation when the key is in a variable or contains special characters.
const car = {
brand: "Toyota",
model: "Corolla",
year: 2024,
"fuel type": "hybrid",
};
console.log(car.brand, car.year);
console.log(car["fuel type"]);
const key = "model";
console.log(car[key]);Toyota 2024 hybrid Corolla
Adding, Updating and Deleting
const user = { name: "Hira" };
user.email = "hira@example.com"; // add
user.name = "Hira K."; // update
delete user.email; // remove
console.log(user);
console.log("email" in user, Object.hasOwn(user, "name"));{
"name": "Hira K."
}
false trueMethods and this
Inside a method, this refers to the object the method was called on. Use the shorthand method syntax, not an arrow function, when you need this.
const account = {
owner: "Faisal",
balance: 500,
deposit(amount) {
this.balance += amount;
return this.balance;
},
};
console.log(account.deposit(250));
console.log(`${account.owner} has ${account.balance}`);750 Faisal has 750
Shorthand Properties and Computed Keys
If a variable has the same name as the key, write it once. Square brackets in the key position compute the key from an expression.
const city = "Karachi";
const pop = 20;
const field = "country";
const info = { city, pop, [field]: "Pakistan" };
console.log(info);{
"city": "Karachi",
"pop": 20,
"country": "Pakistan"
}Looping Through an Object
Object.keys, Object.values and Object.entries turn an object into arrays you can loop over or use with array methods.
const stock = { rice: 120, tea: 300, honey: 0 };
console.log(Object.keys(stock).join(","));
console.log(Object.values(stock).reduce((a, b) => a + b));
for (const [item, qty] of Object.entries(stock)) {
console.log(item.padEnd(6), qty);
}rice,tea,honey 420 rice 120 tea 300 honey 0
Copying Objects
Spread { ...obj } makes a shallow copy and is perfect for creating an updated version of an object. For deep copies of plain data, use structuredClone(obj).
Frequently asked questions
How do I check if a property exists in a JavaScript object?
Use Object.hasOwn(obj, "key") for own properties or "key" in obj, which also checks the prototype chain.
How do I deep copy an object in JavaScript?
Use structuredClone(obj). It copies nested objects, arrays, dates and maps. Spread and Object.assign only copy one level.
Why is this undefined inside my arrow function method?
Arrow functions do not have their own this. Define object methods with the method shorthand, like greet() { ... }.