JS Objects with Real Examples: Beginner Guide

JS Objects with Real Examples: Beginner Guide

Real things have several details at once. A user has a name, an email and an age. A product has a title, a price and a stock count. JS objects let you keep those details together under one name, as pairs of keys and values, so your code reads the way you think about the data.

This guide walks through creating objects, reading and changing them, adding methods, and copying them safely. Every example has its output in a comment so you can check your own results. If you have not met lists yet, our JS arrays guide pairs well with this one.

Creating an object

The most common way is the object literal: curly braces with key: value pairs separated by commas.

const user = {
  name: "Asha",
  age: 28,
  isMember: true
};

console.log(user); // { name: 'Asha', age: 28, isMember: true }

Each key (also called a property name) is a string. The value can be anything: a number, text, an array, another object or even a function.

Reading and changing properties

There are two ways to reach a value. Dot notation is shorter and what you will use most.

const user = { name: "Asha", age: 28 };

console.log(user.name);      // Asha
console.log(user["age"]);    // 28

user.age = 29;               // update
user.city = "Pune";          // add a new property
delete user.name;            // remove one

console.log(user); // { age: 29, city: 'Pune' }

Use bracket notation when the key is stored in a variable or contains characters that dot notation cannot handle, like a space or hyphen.

const field = "city";
const person = { city: "Delhi", "zip-code": "110001" };

console.log(person[field]);       // Delhi
console.log(person["zip-code"]);  // 110001

A small naming tip: pick keys that describe the value (emailAddress, not e) and use one style throughout, usually camelCase. Other developers, and future you, will thank you when the object has fifteen properties.

Does a property exist?

Reading a missing key gives undefined, not an error. To test for a key without confusion, use in:

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

console.log("theme" in settings);  // true
console.log("language" in settings); // false
console.log(settings.volume || 10);  // 10, oops: 0 counts as "falsy"
console.log(settings.volume ?? 10);  // 0, correct: only null/undefined fall back

That last pair is a classic bug. The || operator treats 0 as missing, while ?? only reacts to null and undefined. Our guide to JavaScript operators explains why.

Related reading: JS OOP Explained: Object-Oriented Programming in JavaScript

Methods: functions inside objects

When a property holds a function, we call it a method. Inside it, this refers to the object the method was called on.

const account = {
  owner: "Ravi",
  balance: 500,
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  }
};

console.log(account.deposit(250)); // 750
console.log(account.balance);      // 750

If functions themselves are still new, read JavaScript functions explained first.

Nested objects and safe access

Objects can hold other objects, which is how most real data from servers looks.

const order = {
  id: 101,
  customer: { name: "Meera", address: { city: "Surat" } },
  items: ["pen", "notebook"]
};

console.log(order.customer.address.city);       // Surat
console.log(order.customer.phone?.mobile);      // undefined, no crash

The ?. operator (optional chaining) stops and returns undefined if something along the way is missing. Without it, order.customer.phone.mobile would throw an error, because phone is undefined and you cannot read a property from undefined.

Looping over an object

Three helpers turn an object into arrays you can loop over:

const stock = { apples: 5, pears: 0, plums: 12 };

console.log(Object.keys(stock));   // [ 'apples', 'pears', 'plums' ]
console.log(Object.values(stock)); // [ 5, 0, 12 ]

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count}`);
}
// apples: 5
// pears: 0
// plums: 12

Copying objects the right way

Objects are stored by reference. Assigning one to another variable gives you two names for the same thing.

const original = { name: "Asha", tags: ["a"] };
const alias = original;
alias.name = "Changed";
console.log(original.name); // Changed

const copy = { ...original, name: "Fresh" }; // shallow copy with an override
console.log(original.name, copy.name);      // Changed Fresh

Spread makes a shallow copy. Nested objects and arrays are still shared between the original and the copy. For a fully independent copy, use structuredClone(original), which is built into modern browsers and Node.

Objects and JSON

When you send data to a server or save it in the browser, it has to become plain text first. JSON.stringify turns an object into a JSON string, and JSON.parse turns it back. This is the bridge between your code and the outside world, and it is how APIs usually send data.

const item = { title: "Notebook", price: 40 };

const text = JSON.stringify(item);
console.log(text);               // {"title":"Notebook","price":40}
console.log(typeof text);        // string

const back = JSON.parse(text);
console.log(back.title);         // Notebook

Functions are dropped during this trip, because JSON can only hold plain data such as text, numbers, booleans, arrays and nested objects. Keep that in mind if a method seems to vanish after saving.

Handy shortcuts

  • Shorthand properties: { name, age } uses variables named name and age as both keys and values.
  • Destructuring: const { name, age } = user; pulls out several values in one line.
  • Computed keys: { [field]: "x" } builds a key from a variable.

These all arrived with ES6, and you will see them constantly in modern code.

Common mistakes

  • Writing user.name when the key is stored in a variable. Use user[variable].
  • Expecting a copy when you only made a second reference.
  • Using arrow functions as methods and then finding that this is not the object.
  • Confusing a JSON string with an object. JSON is text; an object is live data in memory.

Find more fundamentals in the JavaScript category.

Conclusion

Objects are how JavaScript describes things. Remember:

  • An object is a set of key and value pairs written in curly braces.
  • Use dot notation by default and brackets for dynamic keys.
  • Functions stored in an object are methods, and this points to their object.
  • Use ?. and ?? for safe, predictable access.
  • Copy with spread or structuredClone, never plain assignment.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Your comment will appear after moderation.