JavaScript Tutorial · Objects and Arrays · Lesson 22 of 44
JavaScript Objects
Create objects, read and update properties, and add methods.
Object literals
An object groups related values as key: value pairs (properties):
const user = {
name: "Ada",
age: 36,
"favourite-language": "JavaScript",
};
console.log(user.name);
console.log(user["favourite-language"]);
user.age = 37; // update
user.email = "[email protected]"; // add
delete user["favourite-language"];
console.log(user);
console.log("email" in user, user.phone);
Output
Ada
JavaScript
{ name: 'Ada', age: 37, email: '[email protected]' }
true undefinedUse dot notation (user.name) normally, and bracket notation (user["first-name"] or user[key]) when the key is dynamic or not a valid identifier.
Methods
A function stored in an object is a method. Inside it, this refers to the object it was called on:
const account = {
owner: "Ada",
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
},
};
account.deposit(50);
console.log(`${account.owner} has $${account.balance}`);
Output
Ada has $150
Shorthand and computed keys
const name = "Ada";
const role = "admin";
const field = "lastLogin";
const user = { name, role, [field]: "2026-10-01" };
console.log(user);
Output
{ name: 'Ada', role: 'admin', lastLogin: '2026-10-01' }Useful Object helpers
Object.keys(), Object.values() and Object.entries() turn an object into arrays; Object.fromEntries() goes back:
const stock = { apples: 5, pears: 0, plums: 12 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
const inStock = Object.fromEntries(Object.entries(stock).filter(([, qty]) => qty > 0));
console.log(inStock);
Output
[ 'apples', 'pears', 'plums' ]
[ 5, 0, 12 ]
{ apples: 5, plums: 12 }Test yourself
How do you read a property whose name is stored in a variable key?
obj.keyobj[key]obj->keyobj{key}
Show answer
Answer: obj[key]