← JavaScript

Basic · 11 of 12 · 17 min read

Objects: the basics

How property keys really work, the difference between dot and bracket access, and the three ways to ask whether a property is there.

  • Objects

An object is a collection of key-value pairs. A value that happens to be a function is called a method, but there is nothing special about it — it is a property like any other.

Creating and reading

const user = {
  name: 'Ana',
  age: 30,
  greet() {
    return `Hi, ${this.name}`; // a method is just a function-valued property
  },
};

console.log(user.name);    // "Ana"
console.log(user['name']); // "Ana" — the same property
console.log(user.greet()); // "Hi, Ana"
console.log(user.missing); // undefined — reading an absent property does not throw

Shorthand for when the variable name is already the key, and computed keys for when it is not known until runtime:

const name = 'Ana';
const field = 'age';

const built = { name, [field]: 30, ['is' + 'Active']: true };
console.log(built); // { name: 'Ana', age: 30, isActive: true }

Dot versus bracket

This is the single most common beginner bug, and it is worth being precise about. Dot notation takes the identifier literally. Bracket notation evaluates the expression.

const user = { name: 'Ana' };
const key = 'name';

console.log(user.key);          // undefined ← looked for a property called "key"
console.log(user[key]);         // "Ana"     ← evaluated `key` to "name"
console.log(user['na' + 'me']); // "Ana"     ← any expression works

So brackets are required whenever the key is dynamic, and also when it is not a valid identifier:

const weird = { 'first name': 'Ana', 'data-id': 7, 2: 'two' };

console.log(weird['first name']); // "Ana"
console.log(weird['data-id']);    // 7
// console.log(weird.first name); // SyntaxError

Keys are strings

Whatever you use as a key gets converted:

const obj = {};
obj[1] = 'number one';
obj['1'] = 'string one';   // the same property — it overwrote the first
obj[true] = 'boolean';
obj[{ a: 1 }] = 'object';

console.log(obj[1], obj['1']);   // "string one" "string one"
console.log(Object.keys(obj));   // ["1", "true", "[object Object]"]

Which is why a Map exists: it keeps keys at their original type.

const key = { id: 1 };

const asObject = { [key]: 'value' };
console.log(Object.keys(asObject)); // ["[object Object]"] — coerced

const asMap = new Map([[key, 'value']]);
console.log(asMap.get(key));        // "value" — the object itself is the key
console.log(asMap.size);            // 1

Symbols are the other legal key type, and they are skipped by the usual inspectors:

const id = Symbol('id');
const tagged = { name: 'Ana', [id]: 7 };

console.log(Object.keys(tagged));    // ["name"]
console.log(JSON.stringify(tagged)); // {"name":"Ana"}
console.log(tagged[id]);             // 7

Does it have the property?

Three checks, three different answers. The difference matters.

Check Finds inherited? Tells undefined from missing?
obj.key !== undefined yes no
'key' in obj yes yes
Object.hasOwn(obj, 'key') no yes
const obj = { a: undefined };

console.log(obj.a !== undefined);     // false ← cannot distinguish the two cases
console.log('a' in obj);              // true
console.log(Object.hasOwn(obj, 'a')); // true

console.log('toString' in obj);              // true  ← inherited from Object.prototype
console.log(Object.hasOwn(obj, 'toString')); // false ← not its own

Object.hasOwn is the modern replacement for obj.hasOwnProperty('key'), which breaks on an object that has no prototype or that has a property of that name:

const dict = Object.create(null);
dict.a = 1;

// console.log(dict.hasOwnProperty('a')); // TypeError — there is no inherited method
console.log(Object.hasOwn(dict, 'a'));    // true

Object.create(null) is the right choice for a lookup table precisely because it inherits nothing — no toString or constructor to collide with your data.

Walking an object

const prices = { apple: 1, banana: 2 };

console.log(Object.keys(prices));    // ["apple", "banana"]
console.log(Object.values(prices));  // [1, 2]
console.log(Object.entries(prices)); // [["apple", 1], ["banana", 2]]

for (const [item, price] of Object.entries(prices)) {
  console.log(item, price); // apple 1 / banana 2
}

All three report own, enumerable, string-keyed properties only. for...in is the one that also walks the prototype chain, which is why it is rarely what you want:

const parent = { inherited: 1 };
const child = Object.create(parent);
child.own = 2;

console.log(Object.keys(child));       // ["own"]
for (const k in child) console.log(k); // "own" then "inherited"

There is no Object.map, so transforming values is a round trip through entries:

const doubled = Object.fromEntries(
  Object.entries(prices).map(([key, value]) => [key, value * 2]),
);
console.log(doubled); // { apple: 2, banana: 4 }

Adding, changing, removing

const user = { name: 'Ana' };

user.age = 30;              // add
user.name = 'Beto';         // change
delete user.age;            // remove
console.log(user);          // { name: 'Beto' }

// `const` blocks rebinding, not mutation:
// user = {};               // TypeError

Object.freeze is what actually prevents mutation — and only one level deep:

const config = Object.freeze({ retries: 3, nested: { debug: false } });

try {
  config.retries = 5;        // TypeError in strict mode (so, in any module)
} catch (e) {
  console.log(e.constructor.name); // TypeError
}

config.nested.debug = true;  // allowed — `nested` was never frozen
console.log(config.retries, config.nested.debug); // 3 true

Copying is shallow

const original = { name: 'Ana', address: { city: 'Rosario' } };

const spread = { ...original };
const assigned = Object.assign({}, original);

spread.name = 'Beto';                 // top level: independent
console.log(original.name);           // "Ana"

spread.address.city = 'Córdoba';      // nested: shared
console.log(original.address.city);   // "Córdoba" ← the same inner object

For a genuinely independent copy:

const deep = structuredClone(original);
deep.address.city = 'Mendoza';
console.log(original.address.city, deep.address.city); // Córdoba Mendoza

JSON.parse(JSON.stringify(obj)) also deep-copies, but only what JSON can express — Date becomes a string, functions and undefined disappear, Map becomes {}, and a circular reference throws.

Comparing objects

By reference, always. Two objects with identical contents are never equal:

console.log({ a: 1 } === { a: 1 }); // false
console.log(Object.is({ a: 1 }, { a: 1 })); // false — not a deep comparison

const x = { a: 1 };
console.log(x === x); // true

Comparing contents means walking both, or serialising — and serialising depends on key order:

const a = { x: 1, y: 2 };
const b = { y: 2, x: 1 };
console.log(JSON.stringify(a) === JSON.stringify(b)); // false — same data, different order

Destructuring

const user = { name: 'Ana', address: { city: 'Rosario' } };

const { name, missing = 'default' } = user;
console.log(name, missing); // Ana default

const { name: label } = user;             // rename
const { address: { city } } = user;       // nested
console.log(label, city);                 // Ana Rosario

const { name: _, ...rest } = { name: 'Ana', age: 30, active: true };
console.log(rest); // { age: 30, active: true }  ← everything else

A default only fires for undefined, never for null:

const { a = 1 } = { a: null };
console.log(a); // null

Common mistakes

Dot notation with a variable key

Mistake. row[column] written as row.column. Why it fails. Dot notation uses the text you typed, so it looks for a property literally named column. What to do instead. Brackets whenever the key is in a variable or built at runtime.

if (obj.flag) to check presence

Mistake. Testing truthiness to mean “the property is set”. Why it fails. false, 0 and '' are all legitimate values and all falsy, and a missing property is indistinguishable from one set to undefined. What to do instead. Object.hasOwn(obj, 'flag') for presence, 'flag' in obj if inherited counts.

Assuming the spread copied everything

Mistake. const copy = { ...state } and then writing to copy.items[0]. Why it fails. Only the top level was copied; copy.items is the same array the original holds. What to do instead. Copy each level you intend to change, or structuredClone for the whole structure.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

This code reads a property whose name is sitting in a variable.

Why does the first value come out undefined?

Code sample
const key = "name";
const user = { name: "Ana" };

console.log(user.key);   // undefined
console.log(user[key]);  // "Ana"

Property keys in a plain object can only ever be one of two types, whatever you write in the brackets.

What does this log?

Code sample
const obj = {};
obj[1] = "a";
console.log(obj["1"]);

You need to know whether an object has a property **of its own**, ignoring anything inherited. What do you use?

Practise Objects →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.