Sub topic 11
Edge Cases: null, Arrays, Strings, and Primitives
Earlier chapters used Object.keys, Object.values, and Object.entries on plain object literals. Real code is messier than that. A function receives null because an API response had no data. A helper meant for objects gets an array, a string, or a Map. This chapter covers what the three methods do with each kind of input, which results surprise people, and how to guard against them.
This chapter assumes you know the following from earlier chapters: the three methods return only own, enumerable, string-keyed properties; integer-like keys come back first in ascending order; and non-enumerable properties such as length are skipped.
The Rule Behind Every Case: Conversion to an Object
All three methods start the same way. They convert their argument to an object using the internal ToObject operation, and then they list that object's own enumerable string keys. Once you know this, every edge case is predictable:
nullandundefinedcannot be converted to an object, so the methods throw aTypeError.- Other primitives (numbers, booleans, strings, symbols, bigints) are wrapped in their wrapper objects (
Number,Boolean,String,Symbol,BigInt). The methods then report whatever own enumerable properties the wrapper has. - Objects of any kind, including arrays, functions, dates, and maps, are used as they are. Only their own enumerable string keys count.
null and undefined Throw
This is the edge case you will hit most often in practice:
const inputs = [null, undefined];
for (const value of inputs) {
try {
Object.keys(value);
} catch (err) {
console.log(err instanceof TypeError, err.message);
}
}
// true Cannot convert undefined or null to object
// true Cannot convert undefined or null to objectThe exact message depends on the engine. The one shown is from V8, which Node.js and Chrome use. Object.values and Object.entries throw in the same way.
The typical bug looks like this: a configuration object has an optional section, and the code loops over it without checking.
const config = { name: 'app' }; // no "plugins" section
try {
for (const [name, options] of Object.entries(config.plugins)) {
console.log(name, options);
}
} catch (err) {
console.log('Crashed:', err.message);
}
// Crashed: Cannot convert undefined or null to objectGuarding with the nullish coalescing operator
The shortest fix is to fall back to an empty object with ??:
const config = { name: 'app' };
for (const [name, options] of Object.entries(config.plugins ?? {})) {
console.log(name, options);
}
console.log('done'); // the loop body never runs
// done?? replaces only null and undefined. You will also see || {}, which replaces every falsy value. For these methods the difference rarely matters, because 0, false, and '' all produce [] anyway. ?? still states the intent more precisely.
A reusable guard
If many places in your code loop over values that might be missing, write the check once:
function entriesOf(value) {
return value == null ? [] : Object.entries(value);
}
console.log(entriesOf({ a: 1 })); // [ [ 'a', 1 ] ]
console.log(entriesOf(null)); // []
console.log(entriesOf(undefined)); // []value == null is the one place where loose equality is idiomatic. It is true for exactly null and undefined.
Before you add a guard, decide whether a missing value is actually allowed. If null signals a bug upstream, an empty loop hides that bug. In that case the TypeError, or an explicit error you throw yourself, is the better outcome.
Number, Boolean, Symbol, and BigInt Return Empty Arrays
The wrapper objects for these primitives have no own enumerable properties, so all three methods return an empty array:
console.log(Object.keys(42)); // []
console.log(Object.values(true)); // []
console.log(Object.entries(Symbol('s'))); // []
console.log(Object.keys(10n)); // []
console.log(Object.keys(NaN)); // []No error is thrown, which can be a problem. If a function expects an object and receives the number 42 by mistake, the loop runs zero times and nothing reports the problem. When the input should always be an object, check its type explicitly. A later section shows how.
Strings Yield Their Indexes
A String wrapper object has one own enumerable property per UTF-16 code unit, keyed '0', '1', and so on. Its length property is own but non-enumerable, so it is skipped:
console.log(Object.keys('hi')); // [ '0', '1' ]
console.log(Object.values('hi')); // [ 'h', 'i' ]
console.log(Object.entries('hi')); // [ [ '0', 'h' ], [ '1', 'i' ] ]
console.log(Object.getOwnPropertyNames('hi')); // [ '0', '1', 'length' ]
console.log(Object.keys('')); // []This rarely causes trouble on purpose, but it does by accident. If a function that turns an object into query parameters gets the string 'abc' instead of { q: 'abc' }, it produces 0=a&1=b&2=c without any error.
Code units, not characters
The indexes count UTF-16 code units. Characters outside the Basic Multilingual Plane, such as most emoji, take two code units. Object.values therefore splits them into two meaningless halves:
const smile = '😀';
console.log(Object.keys(smile).length); // 2
console.log(Object.values(smile)[0] === '😀'); // false: a lone surrogate half
console.log([...smile].length); // 1
console.log([...smile][0] === '😀'); // trueTo loop over the characters of a string, use for...of or spread. Both iterate by code point. Do not use the Object methods for this. Even code points can fall short for text such as flags or emoji with skin-tone modifiers, which combine several code points. For user-visible characters, use Intl.Segmenter.
Arrays: String Indexes, Holes, and Extra Properties
Arrays are objects, so the methods work on them. Their results differ from the array's own iteration methods in three ways.
Indexes come back as strings
const letters = ['x', 'y'];
console.log(Object.keys(letters)); // [ '0', '1' ]
console.log([...letters.keys()]); // [ 0, 1 ]
console.log(Object.entries(letters)); // [ [ '0', 'x' ], [ '1', 'y' ] ]
console.log([...letters.entries()]); // [ [ 0, 'x' ], [ 1, 'y' ] ]String indexes cause real bugs. For example, key + 1 gives '01', not 1, and key === 0 is never true. For arrays, prefer array.keys() and array.entries(). These are methods on the array that return iterators with numeric indexes.
Holes are skipped
A sparse array has missing indexes, which are called holes. A hole has no property at all, so the Object methods skip it. The array iterators visit it and report undefined:
const sparse = ['a', , 'c'];
console.log(sparse.length); // 3
console.log(Object.keys(sparse)); // [ '0', '2' ]
console.log(Object.values(sparse)); // [ 'a', 'c' ]
console.log([...sparse.entries()]); // [ [ 0, 'a' ], [ 1, undefined ], [ 2, 'c' ] ]Which behavior is correct depends on the task. If you need to know which slots actually exist, Object.keys is accurate. If you need one entry per position, use the iterators.
Non-index properties are included
Any extra string-keyed property you add to an array appears in the Object methods. It appears after the indexes, because integer-like keys always come first:
const list = ['a', 'b'];
list.label = 'letters';
console.log(Object.keys(list)); // [ '0', '1', 'label' ]
console.log([...list.keys()]); // [ 0, 1 ]
console.log(list.length); // 2The same rules apply to typed arrays. Object.keys(new Uint8Array(3)) returns ['0', '1', '2'].
Other Built-in Objects: Map, Set, Date, Functions, and Classes
The methods do not know about a type's internal data. They report only own enumerable string-keyed properties, so many built-ins look empty:
const map = new Map([['a', 1]]);
const set = new Set([1, 2]);
console.log(Object.keys(map)); // []
console.log(Object.entries(set)); // []
console.log(Object.keys(new Date())); // []
function greet(name) {}
greet.meta = 'tagged';
console.log(Object.keys(greet)); // [ 'meta' ] (name and length are non-enumerable)
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
get size() {
return Math.hypot(this.x, this.y);
}
}
console.log(Object.keys(new Point(3, 4))); // [ 'x', 'y' ] (the getter lives on the prototype)Calling Object.entries(map) is a common mistake. Maps and sets have their own iteration methods: map.keys(), map.values(), map.entries(), and plain for...of. Use those instead. For class instances, remember that methods and accessors defined in the class body are on the prototype, and private #fields are never listed.
Objects made with Object.create(null) have no prototype, but they work normally with all three methods. That makes the methods safer than calling obj.hasOwnProperty(...), which does not exist on such objects.
Summary Table
| Input | `Object.keys` result | Notes |
|---|---|---|
| `null`, `undefined` | throws `TypeError` | Guard with `?? {}` or `== null` |
| `42`, `true`, `Symbol()`, `10n` | `[]` | Fails silently |
| `'hi'` | `['0', '1']` | Counts UTF-16 code units |
| `['x', , 'z']` | `['0', '2']` | String indexes, holes skipped |
| Array with `.label` | indexes, then `'label'` | Extra properties included |
| `new Map(...)`, `new Set(...)`, `new Date()` | `[]` | Use the type's own iterators |
| Function with `.meta` | `['meta']` | `name`, `length` non-enumerable |
| Class instance | own fields only | Prototype methods and getters excluded |
| `Object.create(null)` with keys | its keys | Works normally |
Accepting Only Plain Objects
When a function should take only plain objects, a null check is not enough. Reject the other inputs explicitly:
function isPlainObject(value) {
if (typeof value !== 'object' || value === null) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function toQuery(params) {
if (!isPlainObject(params)) {
throw new TypeError('toQuery expects a plain object');
}
return Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
}
console.log(toQuery({ q: 'cats', page: 2 })); // q=cats&page=2
for (const bad of ['abc', [1, 2], new Map(), null]) {
try {
toQuery(bad);
} catch (err) {
console.log(err.message);
}
}
// toQuery expects a plain object (printed four times)Checking the prototype rejects arrays, maps, dates, and class instances. That strictness suits serialization code. For general helpers you may only need value == null.
Exercise
Predict the output of console.log(Object.keys([10, , 30]), Object.keys(7), Object.keys('ok')), and say what Object.keys(undefined) does.
Show answer
It prints [ '0', '2' ] [] [ '0', '1' ]. The hole at index 1 is skipped, the number 7 wraps to a Number object with no enumerable properties, and the string yields its index keys as strings. Object.keys(undefined) throws a TypeError because undefined cannot be converted to an object.
Exercise
A teammate writes for (const [i, item] of Object.entries(items)) { if (i === 0) console.log('first:', item); } where items is an array. Why does "first:" never print, and what is the idiomatic fix?
Show answer
Object.entries returns indexes as strings, so i is '0' and '0' === 0 is false. Use items.entries(), which yields numeric indexes: for (const [i, item] of items.entries()). This also visits holes as undefined instead of skipping them.
Exercise
Write a function countKeys(value) that returns 0 for null or undefined, and otherwise the number of own enumerable string keys. What does it return for new Map([['a', 1]]), and why?
Show answer
function countKeys(value) { return value == null ? 0 : Object.keys(value).length; } It returns 0 for the Map, because a Map stores its entries in internal slots, not as properties. Use map.size to count a Map's entries.