Skip to content
Laviyx Learn

Try

JavaScript course menu

JavaScript Objects: Properties, Methods, Keys and Looping

Learn JavaScript objects: object literals, reading and writing properties with dot and bracket notation, adding and deleting properties, shorthand properties, methods, checking if a key exists, Object.keys, values and entries, nested objects, copying and freezing objects.

Beginner11 min readUpdated
On this page

An object groups related data under named properties. Where an array is an ordered list, an object is a collection of key: value pairs, like a profile, a product or a settings panel.

Creating an object#

JavaScript
const student = {
  name: "Asha Rao",
  age: 21,
  course: "JavaScript",
  isEnrolled: true,
  skills: ["HTML", "CSS"],
};

console.log(student);
Output
{
  name: 'Asha Rao',
  age: 21,
  course: 'JavaScript',
  isEnrolled: true,
  skills: [ 'HTML', 'CSS' ]
}

Keys are strings (written without quotes when they are valid names); values can be anything, including arrays, other objects and functions.

Reading properties#

JavaScript
const student = { name: "Asha Rao", age: 21, "favourite colour": "blue" };

console.log(student.name);
console.log(student["age"]);
console.log(student["favourite colour"]);

const field = "name";
console.log(student[field]);
console.log(student.email);
Output
Asha Rao
21
blue
Asha Rao
undefined
  • Dot notation (student.name) is the usual way.
  • Bracket notation (student["age"]) is needed when the key has spaces or special characters, or when the key is in a variable.
  • A missing property gives undefined.

Adding, changing and deleting#

JavaScript
const user = { name: "Ravi" };

user.age = 30;                 // add
user.name = "Ravi Kumar";      // change
user["city"] = "Pune";         // add with brackets
delete user.age;               // remove

console.log(user);
Output
{ name: 'Ravi Kumar', city: 'Pune' }

Shorthand properties and computed keys#

When a property has the same name as a variable, write it once:

JavaScript
const name = "Meera";
const age = 28;
const field = "role";

const person = { name, age, [field]: "Designer" };
console.log(person);
Output
{ name: 'Meera', age: 28, role: 'Designer' }

[field] is a computed key: the key name comes from the variable's value.

Methods#

A function stored in an object is called a method. Inside a method, this refers to the object it was called on:

JavaScript
const cart = {
  items: [120, 450, 80],
  total() {
    return this.items.reduce((sum, p) => sum + p, 0);
  },
  addItem(price) {
    this.items.push(price);
  },
};

cart.addItem(50);
console.log(cart.total());
Output
700

total() { ... } is shorthand for total: function () { ... }. Use this regular method syntax, not arrow functions, for methods that use this (Arrow Functions).

Checking whether a key exists#

JavaScript
const settings = { theme: "dark", fontSize: 0 };

console.log("fontSize" in settings);
console.log(Object.hasOwn(settings, "language"));
console.log(settings.fontSize !== undefined);
Output
true
false
true

Do not test with if (settings.fontSize): a value of 0 is falsy (Truthy and Falsy).

Keys, values and entries#

JavaScript
const prices = { tea: 20, coffee: 35, juice: 50 };

console.log(Object.keys(prices));
console.log(Object.values(prices));
console.log(Object.entries(prices));

for (const [drink, price] of Object.entries(prices)) {
  console.log(`${drink}: ₹${price}`);
}

const doubled = Object.fromEntries(
  Object.entries(prices).map(([k, v]) => [k, v * 2])
);
console.log(doubled);
Output
[ 'tea', 'coffee', 'juice' ]
[ 20, 35, 50 ]
[ [ 'tea', 20 ], [ 'coffee', 35 ], [ 'juice', 50 ] ]
tea: ₹20
coffee: ₹35
juice: ₹50
{ tea: 40, coffee: 70, juice: 100 }

Object.entries plus array methods plus Object.fromEntries is the standard way to transform an object.

Nested objects#

JavaScript
const order = {
  id: 1042,
  customer: { name: "Asha", address: { city: "Hyderabad", pin: "500001" } },
  items: [{ name: "Pen", qty: 2 }],
};

console.log(order.customer.address.city);
console.log(order.items[0].name);
console.log(order.customer.phone?.mobile);
Output
Hyderabad
Pen
undefined

Optional chaining ?. avoids an error when an intermediate property is missing (Operators).

Copying objects#

Like arrays, objects are shared by reference. Spread makes a shallow copy; structuredClone makes a deep copy:

JavaScript
const original = { name: "Asha", address: { city: "Pune" } };

const shallow = { ...original };
const deep = structuredClone(original);

shallow.name = "Changed";
shallow.address.city = "Changed city";

console.log(original.name, original.address.city);
console.log(deep.address.city);
Output
Asha Changed city
Pune

The shallow copy has its own name, but shares the nested address object with the original.

Spread is also how you merge objects or update a property without changing the original: const updated = { ...user, city: "Delhi" }; (later properties win).

Freezing#

Object.freeze stops an object's properties from being changed, added or removed (only at the top level; nested objects are not frozen):

JavaScript
const config = Object.freeze({ apiUrl: "https://api.example.com", retries: 3 });

try {
  config.retries = 10;
} catch (error) {
  console.log(error.name);
}
console.log(config.retries);
Output
TypeError
3

In strict-mode code (modules and classes, like the examples on this site), changing a frozen object throws a TypeError. In old non-strict scripts, the change is silently ignored. Either way, the value stays 3.

Practice#

Practice exercise

Create a book object with title, author, year and ratings (an array of numbers), plus a method averageRating(). Add a pages property, print the title and year with a template literal, and print the average rating rounded to one decimal place.

Show solution
JavaScript
const book = {
  title: "Learning to Code",
  author: "Asha Rao",
  year: 2024,
  ratings: [5, 4, 5, 4, 4],
  averageRating() {
    const sum = this.ratings.reduce((a, b) => a + b, 0);
    return sum / this.ratings.length;
  },
};

book.pages = 320;
console.log(`${book.title} (${book.year})`);
console.log(book.averageRating().toFixed(1));
console.log(Object.keys(book).length);
Output
Learning to Code (2024)
4.4
6

Key takeaway#

Finished this lesson?