An object groups named properties into one value. In a network inventory, an object can represent a switch identifier, port count, rack location and nested counters. Unlike an array, whose ordinary elements use numeric indexes, an object is suited to named fields. Begin with OSJavaScript.006: arrays and compare the two data models.
Prerequisites and learning objectives
Use a local Node.js 22 or newer installation and a disposable directory. Review variables and constants and operators and equality. By completion, learners should construct objects; read and modify properties; distinguish absence from undefined and inherited properties; explain reference identity and shallow copies; isolate nested state; and test safe inventory transformations.
1. Object literals and property access
An object literal uses braces and comma-separated key-value pairs. Ordinary object property keys are strings or symbols; numeric keys are converted to strings. Values may be primitives, objects, arrays or functions. A property can be read with dot notation when its name is a valid identifier, or bracket notation for computed keys and names containing punctuation.
const device = { id: "sw-01", ports: 48, "rack-id": "R12" };
const field = "ports";
console.log(device.id); // sw-01
console.log(device[field]); // 48
console.log(device["rack-id"]); // R12
Dot notation uses the literal property name, so device.field is not equivalent to device[field]. Property access on null or undefined throws a TypeError; optional chaining can return undefined instead when the receiver is nullish. Review primitive values for the difference between null and undefined.
2. Mutation, absence and ownership
Assigning to an existing writable property changes its value. Assigning to a new key on an ordinary extensible object adds a property. The delete operator removes a configurable own property. A const binding cannot be reassigned, but properties of its object can still change. Object.hasOwn(obj, key) distinguishes an absent own property from an existing property whose value is undefined. The in operator also recognizes inherited properties.
device.ports = 32;
device.online = true;
delete device.online;
device.serial = undefined;
console.log(Object.hasOwn(device, "serial")); // true
console.log(Object.hasOwn(device, "toString")); // false
console.log("toString" in device); // true
The final two results assume an ordinary object literal inheriting from Object.prototype. Object.keys returns enumerable own string keys, excluding symbols and inherited keys. Object.entries returns corresponding key-value pairs. Use a for…of loop over the entries for predictable inspection; review OSJavaScript.005 control flow.
Optional instructional media: JavaScript Objects: Comparison, Copying, Merging, Destructuring, and Rest Parameters covers object equality and shallow versus deep copying. The linked video is supplemental; playback could not be independently verified, so no embedded player is included.
3. Object identity and memory architecture
A variable holding an object refers to an object identity rather than containing an independent copy of all its fields. Assignment copies the reference value. Two references to one object observe its mutations. Strict equality between objects checks identity, not matching field contents. JavaScript engines can optimize memory layout; the reference model is a language-level explanation, not a guarantee about physical addresses.
const original = { ports: 48, metrics: { errors: 0 } };
const alias = original;
alias.ports = 24;
console.log(original.ports); // 24
const shallow = { ...original };
shallow.ports = 16;
shallow.metrics.errors = 3;
console.log(original.metrics.errors); // 3
Object spread copies enumerable own properties into a new object. Nested reference values remain shared. A nested spread can deliberately copy a known nested object; structuredClone can clone many supported data types including cyclic data, but not arbitrary functions. It does not preserve every property descriptor or custom prototype. Choose a copy mechanism according to the structure and contract rather than assuming every object is fully independent.
4. Local laboratory: inventory transformations
Save the following standalone CommonJS file as inventory.cjs. The assertions check construction, dynamic keys, ownership, mutation, identity, shallow copying and explicit nested isolation. The readings are synthetic and do not connect to equipment.
const assert = require("node:assert/strict");
const device = {
id: "sw-01",
ports: 48,
"rack-id": "R12",
metrics: { errors: 0 }
};
const field = "ports";
assert.equal(device.id, "sw-01");
assert.equal(device[field], 48);
assert.equal(device["rack-id"], "R12");
assert.equal(device.serial, undefined);
assert.equal(Object.hasOwn(device, "serial"), false);
device.serial = undefined;
assert.equal(Object.hasOwn(device, "serial"), true);
device.ports = 32;
device.online = true;
delete device.online;
assert.equal(Object.hasOwn(device, "online"), false);
const alias = device;
alias.ports = 24;
assert.equal(device.ports, 24);
assert.equal(alias === device, true);
const copy = { ...device };
assert.equal(copy === device, false);
copy.ports = 16;
assert.equal(device.ports, 24);
copy.metrics.errors = 3;
assert.equal(device.metrics.errors, 3);
const separate = { ...device, metrics: { ...device.metrics } };
separate.metrics.errors = 9;
assert.equal(device.metrics.errors, 3);
assert.equal(Object.keys(device).includes("ports"), true);
assert.equal(Object.hasOwn(device, "toString"), false);
assert.equal("toString" in device, true);
console.log("16 checks passed");
Run node –version, then node inventory.cjs from the local directory. Executed on Node.js v22.16.0: all 16 assertions passed. Output: 16 checks passed. A failing assertion reports a mismatch and exits with an error; correct the assumption rather than suppressing the test.
5. Safe design and security boundaries
Never directly merge arbitrary configuration keys into privileged objects. Validate an allowlist of permitted fields and expected value types. Object.hasOwn is useful for ownership checks but does not establish trust or validate values. Reject unexpected keys such as __proto__, constructor and prototype when accepting untrusted dynamic input; consider Map or an appropriate null-prototype dictionary for arbitrary keys. Object spread does not invoke inherited setters on its destination, but nested objects and later merge operations still need validation. For production inventory changes, use authorization, review, testing and rollback.
6. Exercises
A. Create a router with an id and two interface objects in an array. Read the second interface speed using bracket notation. B. Add a property named serial with the value undefined and distinguish it from a missing property. C. Make a shallow copy of an object with a nested array and predict the effect of pushing into the copied array. D. Isolate the array using a second spread. E. Write a function that accepts only a string id and a nonnegative integer port count, returning a new object.
Knowledge check and answer key
1. Does const freeze an object? No; it prevents rebinding. 2. Does strict equality compare contents? No; object identity determines equality. 3. Does spread recursively clone nested values? No. 4. Does Object.hasOwn detect inherited properties? No. 5. Does a successful ownership check mean the value is safe? No; validate it separately.
Exercise answers: A: router.interfaces[1].speed, assuming two entries and a speed field. B: Object.hasOwn(router, “serial”) is true while Object.hasOwn(router, “missing”) is false. C: the original nested array changes because both objects refer to it. D: use { …original, interfaces: […original.interfaces] }; nested objects inside the array remain shared. E: require typeof id === “string”, Number.isInteger(ports) and ports >= 0 before returning { id, ports }; reject invalid data.
Glossary and authoritative references
Property: named member of an object. Own property: directly associated with the object. Prototype: object supplying inherited properties. Reference identity: whether two values refer to the same object. Shallow copy: new outer container with existing nested references. See MDN: working with objects, Object.hasOwn, spread syntax and shallow copying.
We volunteer daily to ensure the credibility of the information on our platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.


Leave a Reply