JavaScript - Objects
Overview
Estimated time: 30–40 minutes
Objects are key–value collections. Create them with literals, read/write properties, and add methods. You'll also see handy utilities like Object.keys
, Object.entries
, and Object.assign
.
Learning Objectives
- Create objects with literals and
Object.create
. - Access properties (dot/bracket), computed keys, and methods.
- Use common utilities:
keys
,values
,entries
,assign
,fromEntries
.
Prerequisites
Object literal and property access
const user = { id: 1, name: 'Ada' };
user.name; // 'Ada' (dot access)
user['name']; // 'Ada' (bracket)
const key = 'role';
user[key] = 'admin'; // computed key
user.greet = function(){ return `Hi ${this.name}`; };
Shorthand and computed keys
const name = 'Lin';
const role = 'editor';
const profile = { name, role, ['is-' + role]: true };
Enumerating properties
Object.keys(user); // ['id','name','role','greet']
Object.values(user); // [1,'Ada','admin', function]
Object.entries(user); // [['id',1], ['name','Ada'], ...]
const pairs = [['x',10], ['y',20]];
Object.fromEntries(pairs); // { x:10, y:20 }
Copying/merging objects
const u1 = { id: 1, tags: ['a'] };
const u2 = { ...u1, name: 'Ada' }; // shallow copy via spread
const u3 = Object.assign({}, u1, { name: 'Ada' });
Common Pitfalls
- Spread/assign are shallow: nested objects/arrays are shared references.
- Using
in
includes inherited keys; for own keys useObject.hasOwn(obj, key)
orObject.prototype.hasOwnProperty.call(obj, key)
in older environments.
Checks for Understanding
- What’s the difference between dot and bracket property access?
- Why is
Object.assign
considered a shallow copy?
Show answers
- Dot requires a valid identifier known at author time; bracket works with strings or computed keys at runtime.
- It copies only the top-level properties; nested objects/arrays are still shared references.
Exercises
- Write a function that returns an object from an array of key/value pairs using
Object.fromEntries
. - Clone an object with nested arrays and prove why a shallow copy is not enough.