JS

Objects

JavaScript · 10 entries

Creating Objects

syntax
const obj = { key: value };
const obj = Object.create(proto);
example
const user = {
  name: "Kai",
  age: 30,
  greet() {
    return `Hi, I'm ${this.name}`;
  }
};
console.log(user.greet());
output
"Hi, I'm Kai"

Note Method shorthand greet() {} is preferred over greet: function() {}. Arrow functions should not be used as methods because they do not bind their own this.

Accessing Properties

syntax
obj.property
obj["property"]
obj[variable]
example
const config = { "max-retries": 3, timeout: 5000 };
console.log(config.timeout);          // 5000
console.log(config["max-retries"]);   // 3

const key = "timeout";
console.log(config[key]);             // 5000

Note Use bracket notation for dynamic keys or keys with special characters. Dot notation is cleaner for static, valid-identifier keys.

Property Shorthand and Computed Keys

syntax
const obj = { name, [expression]: value };
example
const name = "Mira";
const role = "admin";
const user = { name, role };
console.log(user); // { name: "Mira", role: "admin" }

const field = "email";
const form = { [field]: "mira@example.com" };
console.log(form); // { email: "mira@example.com" }

Note Shorthand works when the variable name matches the desired key name. Computed keys are evaluated at runtime.

Object Destructuring in Function Parameters

syntax
function fn({ key1, key2 = default }) {}
example
function createUser({ name, role = "viewer", active = true }) {
  return { name, role, active, createdAt: Date.now() };
}

const admin = createUser({ name: "Bo", role: "admin" });
console.log(admin);
output
{ name: "Bo", role: "admin", active: true, createdAt: ... }

Note Destructuring in parameters makes function signatures self-documenting. Add = {} as a default to allow calling with no arguments: function fn({ x } = {}).

Object.keys / values / entries

syntax
Object.keys(obj)
Object.values(obj)
Object.entries(obj)
example
const inventory = { apples: 5, bananas: 12, cherries: 30 };

console.log(Object.keys(inventory));    // ["apples", "bananas", "cherries"]
console.log(Object.values(inventory));  // [5, 12, 30]

for (const [fruit, count] of Object.entries(inventory)) {
  console.log(`${fruit}: ${count}`);
}

Note These only return own enumerable string-keyed properties. Symbol keys and inherited properties are excluded.

Merging Objects

syntax
Object.assign(target, ...sources)
{ ...obj1, ...obj2 }
example
const defaults = { theme: "light", lang: "en", debug: false };
const userPrefs = { theme: "dark", debug: true };

const settings = { ...defaults, ...userPrefs };
console.log(settings);
output
{ theme: "dark", lang: "en", debug: true }

Note Both approaches are shallow. Later sources overwrite earlier ones. Use structuredClone for deep merging or a library for recursive merge.

Freezing and Sealing Objects

syntax
Object.freeze(obj)
Object.seal(obj)
Object.isFrozen(obj)
example
const API = Object.freeze({
  BASE_URL: "https://api.example.com",
  VERSION: 2,
});
API.VERSION = 3;            // silently fails (throws in strict mode)
console.log(API.VERSION);   // 2

Note freeze() prevents all changes. seal() allows modifying existing properties but not adding/removing. Both are shallow -- nested objects remain mutable.

Checking Property Existence

syntax
Object.hasOwn(obj, prop)
"prop" in obj
example
const user = { name: "Lina", age: 28 };

console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log("toString" in user);           // true (inherited)
console.log(Object.hasOwn(user, "toString")); // false

Note Object.hasOwn() (ES2022) replaces obj.hasOwnProperty(). It works even if the object was created with Object.create(null).

Object.fromEntries()

syntax
Object.fromEntries(iterable)
example
const params = new URLSearchParams("page=2&sort=name&order=asc");
const queryObj = Object.fromEntries(params);
console.log(queryObj);

// Transform values
const prices = { shirt: 25, jacket: 120, cap: 15 };
const discounted = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 0.9])
);
console.log(discounted);
output
{ page: "2", sort: "name", order: "asc" }
{ shirt: 22.5, jacket: 108, cap: 13.5 }

Note The inverse of Object.entries(). Takes any iterable of [key, value] pairs including Maps.

Deep Cloning Objects

syntax
structuredClone(obj)
example
const original = {
  user: { name: "Kai", tags: ["admin", "editor"] },
  updatedAt: new Date(),
};
const clone = structuredClone(original);
clone.user.tags.push("viewer");

console.log(original.user.tags); // ["admin", "editor"]

Note Handles circular references, Dates, Maps, Sets, ArrayBuffers, and more. Does NOT clone functions, Errors, or DOM nodes.