TExcelTAD
Home › JavaScript › JS Object Properties & Methods

JavaScript Object Properties & Methods

The previous chapter introduced objects. This one looks at the tools for working with their properties: checking whether a property exists, looping over keys and values, copying and merging objects, and the built-in Object helper methods.

Checking for a property

Reading a missing property gives undefined, but a property can also exist with the value undefined. To check existence, use in or Object.hasOwn():

js · try it yourself
const profile = { name: "Ines", nickname: undefined };

console.log(profile.nickname === undefined);   // true, but...
console.log("nickname" in profile);            // it exists
console.log("age" in profile);                 // this one doesn't
console.log(Object.hasOwn(profile, "name"));
console.log("toString" in profile);            // inherited from Object.prototype
console.log(Object.hasOwn(profile, "toString"));
true
true
false
true
true
false

in also finds inherited properties; Object.hasOwn only counts the object's own properties.

Keys, values and entries

Object.keys(), Object.values() and Object.entries() turn an object into arrays you can loop over or transform:

js · try it yourself
const stock = { apples: 12, pears: 0, plums: 7 };

console.log(Object.keys(stock));
console.log(Object.values(stock));
console.log(Object.entries(stock));

for (const [fruit, qty] of Object.entries(stock)) {
  console.log(`${fruit.padEnd(7)} ${qty > 0 ? qty : "sold out"}`);
}

const total = Object.values(stock).reduce((sum, n) => sum + n, 0);
console.log("Total:", total);
[ 'apples', 'pears', 'plums' ]
[ 12, 0, 7 ]
[ [ 'apples', 12 ], [ 'pears', 0 ], [ 'plums', 7 ] ]
apples  12
pears   sold out
plums   7
Total: 19

Object.fromEntries() does the reverse — it builds an object from [key, value] pairs. Together they let you "map" over an object:

js · try it yourself
const prices = { tea: 2, coffee: 3, cake: 4.5 };
const discounted = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 0.9])
);
console.log(discounted);
{ tea: 1.8, coffee: 2.7, cake: 4.05 }

Copying and merging

The spread syntax { ...obj } and Object.assign() copy properties into a new object. When the same key appears more than once, the last one wins — a neat way to apply overrides to defaults:

js · try it yourself
const defaults = { theme: "light", fontSize: 14, showTips: true };
const userPrefs = { theme: "dark" };

const settings = { ...defaults, ...userPrefs };
console.log(settings);

const merged = Object.assign({}, defaults, { fontSize: 18 });
console.log(merged);
{ theme: 'dark', fontSize: 14, showTips: true }
{ theme: 'light', fontSize: 18, showTips: true }

Both copies are shallow: nested objects are shared, not duplicated. For a deep copy of plain data use structuredClone(obj).

Computed property names

Square brackets inside an object literal let you compute a key from an expression:

js · try it yourself
const field = "email";
const id = 7;
const record = {
  [field]: "sam@example.com",
  [`item_${id}`]: true,
};
console.log(record);
{ email: 'sam@example.com', item_7: true }

Useful Object methods

Method What it does
Object.keys(o) array of own property names
Object.values(o) array of own property values
Object.entries(o) array of [key, value] pairs
Object.fromEntries(pairs) object from [key, value] pairs
Object.assign(target, ...src) copy properties into target
Object.hasOwn(o, key) does o itself have key?
Object.freeze(o) make properties read-only
Object.seal(o) allow changes, forbid adding/removing
structuredClone(o) deep copy (not a method of Object, but closely related)

Displaying objects

Joining an object into a string gives the unhelpful [object Object]. Use JSON.stringify() or log the object directly:

js · try it yourself
const point = { x: 3, y: 4 };
console.log("Point: " + point);
console.log("Point: " + JSON.stringify(point));
console.log("Point:", point);
Point: [object Object]
Point: {"x":3,"y":4}
Point: { x: 3, y: 4 }

Tip: In console.log, pass objects as separate arguments (with a comma) instead of concatenating with +, and you'll see their full contents.

Test yourself

Which returns an array of [key, value] pairs?

  1. Object.keys()
  2. Object.values()
  3. Object.entries()
  4. Object.pairs()

What is { ...{ a: 1, b: 2 }, ...{ b: 3 } }?

  1. { a: 1, b: 2 }
  2. { a: 1, b: 3 }
  3. { b: 3 }
  4. { a: 1, b: [2, 3] }

What does "x" in obj check?

  1. Whether obj.x is truthy
  2. Whether the property exists (own or inherited)
  3. Whether obj has a value "x"
  4. Whether obj is a string