Explain it simply
Explain it simply
Think of an ID card. It holds pairs of labels and values: "Name: Aung Aung", "Age: 30", "City: Yangon". Everything on it belongs to one person, so it lives on one card. To find the age, you simply look for the "Age" label.
A JavaScript object is that card. It gathers key: value pairs, called properties, inside curly braces, as in { firstName: "Aung", age: 30 }, and you read one with person.age. Instead of juggling three separate variables, related data travels together under one name.
Problem → Why → Solution
The problem: editing a draft changes the original profile
A profile form lets the user edit a draft copy, so that pressing Cancel can show the original again. After editing the name and cancelling, the original name is intact. But after editing the city and cancelling, the original profile's city has changed too.
const user = { name: "Su", address: { city: "Yangon" } };
const draft = { ...user }; // looks like a full copy
draft.name = "Su Su"; // fine: top-level value was copied
draft.address.city = "Mandalay"; // nested object is shared!
console.log(user.name); // Su
console.log(user.address.city); // Mandalay (the original changed)Why did the city change too?
Object variables do not hold the object itself; they hold a reference to where it lives. {...user} copies the top-level properties into a new object, but the value of address is a reference, so only the reference is copied. draft.address and user.address therefore point at the same address object, and a change through one is visible through the other. This is called a shallow copy.
Core concept: properties, references and safe access
In an object literal { key: value, ... }, keys are strings and values can be anything: numbers, strings, arrays, other objects, even functions. There are two ways to read a property. Dot notation, person.age, is for keys you know while writing the code. Bracket notation, person["age"] or person[key], is for keys held in a variable or keys with spaces or dashes such as "first-name".
Reading a missing property gives undefined, not an error. Reading a property of that undefined, as in user.address.city when there is no address, throws a TypeError. Optional chaining, user.address?.city, returns undefined instead of crashing when the left side is null or undefined, and ?? (nullish coalescing) swaps that undefined for a default. Assigning person.city = "Yangon" adds or updates a property, and delete person.city removes it.
A property whose value is a function is called a method. When you call person.fullName(), this inside the method is the object to the left of the dot, person; a later lesson covers this in depth.
The most important idea is that objects are handled by reference. const b = a; does not create a new object; it only gives the same object a second name, so a change made through b is visible through a. === does not compare contents either; it asks whether both sides are the same object, so { x: 1 } === { x: 1 } is false. Declaring with const only stops the variable from pointing at a different object; the properties inside can still change. To copy nested objects as well, use structuredClone().
To walk every property, Object.keys(obj) returns an array of keys, Object.values(obj) an array of values, and Object.entries(obj) an array of [key, value] pairs, any of which you can loop over with for...of. To test whether a property exists, use "phone" in user or Object.hasOwn(user, "phone"); both tell a key holding undefined apart from a key that is not there at all.
- { } creates a new object
- A variable stores a reference to it
- b = a copies only the reference
- Edits through a or b hit one object
You only get a new object when something creates one: a { } literal or a copy function.
General pattern
const objectName = {
key: value,
methodName() {
return this.key;
},
};
objectName.key; // dot notation
objectName[variableKey]; // bracket notation
objectName.newKey = value; // add or update
objectName.maybe?.deeper ?? fallback; // safe readProperties are separated by commas, and methodName() { } is the short way to write a method. The lines below show reading, reading with a variable key, adding or updating, and a safe read with a fallback.
Example: a person object with a method
The person object has three data properties and one method. In a few lines you will see a dot read, a method call, a read through a variable key and a new property being added.
const person = {
firstName: "Aung",
lastName: "Hla",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.firstName);
console.log(person.fullName());
const key = "age";
console.log(person[key]);
person.city = "Yangon";
console.log(Object.keys(person));Code breakdown
- Lines 5-7
fullName: function() {The value is a function, so fullName is a method. Called as person.fullName(), this is person and this.firstName is "Aung".
- Line 10
console.log(person.firstName);The key is known while writing the code, so dot notation fits. It prints "Aung".
- Line 11
console.log(person.fullName());The parentheses run the method, which returns "Aung Hla". Without them you would print the function itself.
- Lines 13-14
console.log(person[key]);The variable key holds "age", so bracket notation reads person.age and gives 30. Writing person.key would look for a property literally named "key" and return undefined.
- Lines 15-16
person.city = "Yangon";person was declared with const, yet a new property can still be added. Object.keys() returns the keys as an array in the order they were added.
Aung
Aung Hla
30
[ 'firstName', 'lastName', 'age', 'fullName', 'city' ]References, copies and safe access in action
const b = a copies the reference, not the object
------------------------------------------------
variable heap
+-------+
| a |----+
+-------+ | +----------------+
+---->| { score: 99 } |
+-------+ | +----------------+
| b |----+
+-------+
b.score = 99 changes the one object both names point toThe snippet below lets you run each idea: a shared reference, === checking identity, structuredClone() copying nested objects too, and ?. with ?? reading missing properties safely.
const a = { score: 1 };
const b = a;
b.score = 99;
console.log(a.score); // 99: same object
console.log({ x: 1 } === { x: 1 }); // false: two different objects
const user = { name: "Su", address: { city: "Yangon" } };
const deep = structuredClone(user);
deep.address.city = "Mandalay";
console.log(user.address.city); // Yangon: nested object was copied too
const settings = { theme: "dark" };
console.log(settings.fontSize ?? 14); // 14
console.log(user.phone?.number ?? "none"); // none, no TypeErrorLooping over an object
Suppose a settings page must list every setting as "name: value". Object.entries() hands you each property as a [key, value] array, and for...of walks them one by one. Keys come back in the order they were added, except that integer-like keys come first in ascending order.
const settings = { theme: "dark", fontSize: 16, notifications: true };
for (const entry of Object.entries(settings)) {
console.log(entry[0] + ": " + entry[1]);
}
console.log("Has theme?", "theme" in settings);
console.log("Has language?", Object.hasOwn(settings, "language"));In real projects
Where objects show up in real projects
Every JSON response from an API becomes an object once it reaches JavaScript, so user profiles, products and orders are all objects. A profile usually mixes required fields such as email with optional ones such as phone or address. Reading the optional ones as profile.phone ?? "not provided" keeps one missing field from crashing the whole page.
Libraries such as React and Redux expect immutable updates: instead of editing state in place, you build a new object, because they compare old and new objects with === to detect a change. Profile update functions therefore return a fresh object made with a spread copy, and copy the nested address separately as well. A test that checks the original object is unchanged after an update catches exactly the bug from the problem section.
Common mistakes
Common mistakes
1. Reading a variable key with a dot
With const field = "email";, user.field looks for a property literally called "field" and returns undefined. When the key lives in a variable, always use bracket notation: user[field].
2. Treating a spread copy as a deep copy
{...user} copies only the top level, so editing a nested object still changes the original. Spread the nested level yourself, { ...user, address: { ...user.address } }, or use structuredClone(user).
3. Comparing two objects with ===
Two objects with identical contents compare as false with ===, because === only asks whether both sides are the same object. To compare contents, compare the properties you care about one by one.
Best practices
Best practices
- Write functions that return a new object instead of editing the object they received; bugs become easier to trace.
- Name properties consistently in camelCase, such as firstName, so dot notation always works.
- Read every optional API field with ?. and ??, and define its default value in one place.
Mini challenge
Mini challenge: update a profile without touching the original
Write updateProfile(), which takes a profile and an object of changes and returns a new object, and describeProfile(), which reads the optional phone field safely.
- updateProfile must not change the original profile or its nested address
- When changes include an address, replace only the fields given and keep the others, such as zip
- describeProfile shows "not provided" with ?? when phone is missing
- After updating, print the original and the new profile and check they are not the same object
function updateProfile(profile, changes) {
// TODO: copy the top level and apply changes
// TODO: copy address separately and merge changes.address into it
// TODO: return the new object
}
function describeProfile(profile) {
// TODO: "Name (City), phone: ..." with "not provided" as the fallback
}
const original = {
name: "Aye Aye",
email: "aye@example.com",
address: { city: "Yangon", zip: "11181" },
};
// TODO: update email and city, then print new values, old values and identity checksExpected: aye.aye@example.com Mandalay 11181 aye@example.com Yangon Same object? false Same address? false Aye Aye (Mandalay), phone: not provided
Show hint
Merge the top level with { ...profile, ...changes }, then rebuild address separately with { ...profile.address, ...changes.address }. If changes.address is undefined, spreading it simply adds nothing.
Show solution
function updateProfile(profile, changes) {
const updated = { ...profile, ...changes };
updated.address = { ...profile.address, ...changes.address };
return updated;
}
function describeProfile(profile) {
const phone = profile.phone ?? "not provided";
return profile.name + " (" + profile.address.city + "), phone: " + phone;
}
const original = {
name: "Aye Aye",
email: "aye@example.com",
address: { city: "Yangon", zip: "11181" },
};
const updated = updateProfile(original, {
email: "aye.aye@example.com",
address: { city: "Mandalay" },
});
console.log(updated.email, updated.address.city, updated.address.zip);
console.log(original.email, original.address.city);
console.log("Same object?", updated === original);
console.log("Same address?", updated.address === original.address);
console.log(describeProfile(updated));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An object groups key: value properties under one name; use a dot for known keys and brackets for keys in variables.
- Missing properties give undefined, and ?. with ?? let you read nested data without crashing.
- Object variables hold references, so b = a creates no new object and === checks identity.
- {...obj} is only a shallow copy; copy nested objects separately or use structuredClone().
MDN — JavaScript Guide — MDN Web Docs