What is an object?
An object is a collection of key-value pairs (properties), where keys are strings or symbols and values can be anything, including functions (methods); almost everything non-primitive in JavaScript is an object.
Creating objects
- Literal:
{ name: "Ada", greet() {} }, the most common. - Class instances:
new User(). Object.create(proto): with a chosen prototype, orObject.create(null)for a dictionary with no inherited keys.Object.fromEntries(pairs): from[key, value]pairs.
Working with properties
- Read:
obj.nameorobj["name"](bracket notation for dynamic keys). - Check existence:
Object.hasOwn(obj, "key")(modern replacement forhasOwnProperty) or"key" in obj(includes inherited keys). - Delete:
delete obj.key. - Iterate:
Object.keys,Object.values,Object.entries, orfor...in(includes inherited enumerable keys). - Computed keys:
{ [dynamicKey]: value }. - Shorthand:
{ name, age }instead of{ name: name, age: age }.
Reference semantics
Variables hold a reference to the object. Assigning or passing it does not copy it, so two variables can change the same object. Copy with spread (shallow) or structuredClone (deep).
Locking objects
Object.freeze (no changes), Object.seal (no new or deleted keys), Object.preventExtensions (no new keys).
Map vs object
Use a Map for dynamic keys, non-string keys, frequent additions and removals, or when you need insertion-ordered iteration with a size.
Code example
1const key = "level";2const user = {3 name: "Ada",4 skills: ["js"],5 [key]: 3, // computed key6 greet() {7 return `Hi, I'm ${this.name}`;8 },9};1011console.log(user.greet(), user["level"]); // Hi, I'm Ada 312console.log(Object.keys(user)); // ["name", "skills", "level", "greet"]13console.log(Object.hasOwn(user, "name"), "toString" in user); // true true (inherited)1415for (const [k, v] of Object.entries(user)) {16 if (typeof v !== "function") console.log(k, "=>", v);17}1819// Build an object from pairs, and transform one20const prices = Object.fromEntries([["apple", 1], ["pear", 2]]);21const doubled = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, v * 2]));22console.log(doubled); // { apple: 2, pear: 4 }2324// References: both names point to the same object25const alias = user;26alias.name = "Grace";27console.log(user.name); // Grace2829const frozen = Object.freeze({ x: 1 });30frozen.x = 2; // ignored (throws in strict mode)31console.log(frozen.x); // 1
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.