JavaScript Object Properties: Testing, Listing and Deleting (in, Object.hasOwn, Object.keys, Object.entries)
Checking whether a property exists (in, Object.hasOwn, hasOwnProperty, missing vs undefined), listing properties with Object.keys, values, entries, getOwnPropertyNames and Reflect.ownKeys, key order, Object.fromEntries, Object.groupBy and delete.
kvi5hnuCode Sprout team member6 min readOn this page
An object is a set of properties, and three questions come up constantly: does it have this property?, what properties does it have? and how do I remove one? JavaScript has several tools for each, and the differences between them (own or inherited, enumerable or not, string or symbol) are a favorite interview topic. This article sorts them out.

Testing whether a property exists
in: own or inherited
"name" in obj is true if the object has the property anywhere on its prototype chain (article 33):
const base = { inherited: 1 };
const item = Object.create(base);
item.own = undefined;
console.log("own" in item, "inherited" in item, "toString" in item, "missing" in item);
true true true false
Object.hasOwn: own properties only
Object.hasOwn(obj, key) (ES2022) is true only for the object's own properties, enumerable or not:
const base = { inherited: 1 };
const item = Object.create(base);
item.own = "yes";
console.log(Object.hasOwn(item, "own"), Object.hasOwn(item, "inherited"), Object.hasOwn(item, "toString"));
true false false
Before ES2022, the standard tool was the inherited method obj.hasOwnProperty(key). It still works, but it can break: objects from Object.create(null) don't have it, and data can contain a key named hasOwnProperty that shadows it:
const tricky = { hasOwnProperty: () => true }; // e.g. parsed from JSON input
console.log(tricky.hasOwnProperty("x"), Object.hasOwn(tricky, "x"));
const dict = Object.create(null);
dict.a = 1;
try {
dict.hasOwnProperty("a");
} catch (err) {
console.log(err.name);
}
console.log(Object.hasOwn(dict, "a"));
true false
TypeError
true
Old code worked around this with Object.prototype.hasOwnProperty.call(obj, key). Use Object.hasOwn in new code (ESLint's prefer-object-has-own).
propertyIsEnumerable
obj.propertyIsEnumerable(key) is true only for own, enumerable properties. You'll rarely need it; it matters when you work with properties defined as non-enumerable (part 14).
Missing vs present-but-undefined
Comparing with undefined is a quick check, and often good enough, but it can't tell a missing property from one whose value is undefined:
const profile = { nickname: undefined };
console.log(profile.nickname !== undefined, profile.age !== undefined); // both false
console.log("nickname" in profile, "age" in profile); // in tells them apart
false false
true false
The difference matters for things like "did the user explicitly clear this field?" or update payloads where { nickname: undefined } means something different from leaving it out. Use in or Object.hasOwn when it matters; use obj.prop !== undefined (or obj.prop ?? fallback) when it doesn't.
Which test to use
| Question | Use |
|---|---|
| Does the object itself have this key? | Object.hasOwn(obj, key) |
| Can I access this key, inherited or not? | key in obj |
| Is there a usable value? | obj.key !== undefined, or obj.key ?? fallback |
| Is it a method I can call? | typeof obj.key === "function" |
Listing properties
Object.keys, values and entries
The three everyday tools list the object's own, enumerable, string-keyed properties:
const stock = { pens: 3, ink: 0, pads: 12 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
console.log(Object.entries(stock));
for (const [name, count] of Object.entries(stock)) {
if (count === 0) console.log(`reorder ${name}`);
}
[ 'pens', 'ink', 'pads' ]
[ 3, 0, 12 ]
[ [ 'pens', 3 ], [ 'ink', 0 ], [ 'pads', 12 ] ]
reorder ink
They return real arrays, so you can use every array method on them. Object.keys(obj).length === 0 is the standard "is this object empty?" check.
The complete lists
To see everything an object has, including properties that keys skips:
const item = Object.create({ inherited: 1 });
item.visible = 1;
item[Symbol("meta")] = 2;
Object.defineProperty(item, "hidden", { value: 3, enumerable: false });
console.log(Object.keys(item));
console.log(Object.getOwnPropertyNames(item)); // + non-enumerable strings
console.log(Object.getOwnPropertySymbols(item)); // symbols only
console.log(Reflect.ownKeys(item)); // every own key
const viaForIn = [];
for (const k in item) viaForIn.push(k);
console.log(viaForIn); // + inherited enumerable
[ 'visible' ]
[ 'visible', 'hidden' ]
[ Symbol(meta) ]
[ 'visible', 'hidden', Symbol(meta) ]
[ 'visible', 'inherited' ]
for...in (article 42) is the only one that includes inherited properties, which is why modern code prefers Object.keys/entries with for...of.
Key order
All these functions, plus JSON.stringify and spread, list own keys in a fixed order:
- Integer-like keys (
"0","5","42") in ascending numeric order; - Other string keys, including
"-1"and"1.5", in the order they were created; - Symbol keys, in the order they were created.
const first = Symbol("first"), second = Symbol("second");
const mixed = { [second]: 1, z: 1, 5: 1, "-1": 1, 1.5: 1, 0: 1, [first]: 1, a: 1 };
console.log(Reflect.ownKeys(mixed));
[ '0', '5', 'z', '-1', '1.5', 'a', Symbol(second), Symbol(first) ]
Keys for numeric IDs therefore come back sorted, not in insertion order. When the order of arbitrary keys matters, use a Map.
Primitives and null
Object.keys("hi") gives [ '0', '1' ], because the string is wrapped in an object first; numbers and booleans give []. Object.keys(null) and Object.keys(undefined) throw a TypeError.
Transforming objects: entries and fromEntries
Object.fromEntries (ES2019) is the inverse of Object.entries: it builds an object from [key, value] pairs. Together they let you map and filter objects with array methods:
const stock = { pens: 3, ink: 0, pads: 12 };
const inStock = Object.fromEntries(Object.entries(stock).filter(([, count]) => count > 0));
const doubled = Object.fromEntries(Object.entries(stock).map(([name, count]) => [name, count * 2]));
console.log(inStock);
console.log(doubled);
console.log(Object.fromEntries(new URLSearchParams("q=js&page=2"))); // any iterable of pairs
{ pens: 3, pads: 12 }
{ pens: 6, ink: 0, pads: 24 }
{ q: 'js', page: '2' }
It accepts any iterable of pairs, so it also converts a Map or URL query parameters to a plain object.
Grouping: Object.groupBy
Object.groupBy(items, callback) (ES2024) groups the elements of an array, or any iterable, into an object whose keys are the callback's return values:
const people = [
{ name: "Ana", team: "red" },
{ name: "Bo", team: "blue" },
{ name: "Cy", team: "red" },
];
const byTeam = Object.groupBy(people, (person) => person.team);
console.log(byTeam.red.map((p) => p.name), byTeam.blue.length);
console.log(Object.getPrototypeOf(byTeam));
[ 'Ana', 'Cy' ] 1
null
The result is a null-prototype object (article 46), so a group named "constructor" can't collide with anything. If the group keys aren't strings, Map.groupBy returns a Map instead. Before ES2024, this took a reduce call or a library such as Lodash.
Deleting properties
delete obj.key removes an own property, the property itself and not just its value (article 37):
const draft = { title: "Notes", tmp: true };
console.log(delete draft.tmp, "tmp" in draft, delete draft.notThere, draft);
true false true { title: 'Notes' }
deletereturns true when the property is gone afterwards, including when it never existed.- It can't delete inherited properties (delete them from the prototype, which affects everyone) or non-configurable ones: those return false in sloppy mode and throw a
TypeErrorin strict mode. - Setting
obj.key = undefinedis different: the key stays andinis still true. - To get a copy without some keys, without mutating, use rest destructuring (article 28):
const { tmp, ...clean } = draft;.
Common questions
How do I check if an object is empty?
Object.keys(obj).length === 0 checks own enumerable string keys, which is what you want for plain data. For a Map or Set, check size === 0. Note that { a: undefined } is not empty.
Are Object.keys and for...in the same?
No. for...in also visits inherited enumerable properties. With plain object literals there's nothing enumerable to inherit, so they usually agree, but with Object.create, old-style constructor prototypes, or libraries that modify prototypes, they differ.
Why use Object.hasOwn instead of in for data objects?
Because in sees inherited names: "toString" in {} is true. When keys come from data ("does the config set timeout?"), you mean "does this object have it", which is Object.hasOwn.
Is delete slow?
Deleting properties can change an object's internal "shape" and make later accesses slower in hot code. That matters for performance-critical loops, not for everyday code. If you add and remove keys frequently, a Map is designed for exactly that.
Summary
key in objchecks own and inherited properties;Object.hasOwn(obj, key)checks own properties only and is the safe replacement forhasOwnProperty.obj.key !== undefinedcan't distinguish a missing key from one set toundefined;inandObject.hasOwncan.Object.keys,valuesandentrieslist own, enumerable string keys;getOwnPropertyNamesadds non-enumerable ones;getOwnPropertySymbolslists symbols;Reflect.ownKeyslists all own keys;for...inadds inherited enumerable keys.- Own keys are ordered: integer-like keys ascending, then other strings by creation, then symbols by creation.
Object.fromEntries(Object.entries(obj).map(...))maps and filters objects;Object.groupBygroups items into a null-prototype object.deleteremoves own, configurable properties; use rest destructuring for a copy without certain keys.
Practice Questions
What does this print?
const o = Object.create({ a: 1 });
o.b = 2;
console.log("a" in o, Object.hasOwn(o, "a"), Object.keys(o));
Answer
true false [ 'b' ]. a is inherited: in sees it, Object.hasOwn and Object.keys don't.
Write a function that returns a copy of an object with every string value trimmed and other values unchanged.
Answer
const trimAll = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, typeof v === "string" ? v.trim() : v]));
What does this return?
Object.keys({ b: 1, 10: 1, a: 1, 2: 1 })
Answer
[ '2', '10', 'b', 'a' ]: integer-like keys first in ascending order, then the other keys in insertion order.
Group [1, 2, 3, 4, 5, 6] into an object with keys "even" and "odd".
Answer
Object.groupBy([1, 2, 3, 4, 5, 6], (n) => (n % 2 === 0 ? "even" : "odd"))
Gives { odd: [1, 3, 5], even: [2, 4, 6] } (with a null prototype). The keys appear in the order the groups were first seen.
Previous: JavaScript Object Properties: Reading, Writing, Dynamic Keys and Inheritance
Next: Copying and Merging Objects in JavaScript: Object.assign, Spread, Defaults and Deep Merge

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.