Sub topic 11
Edge Cases: null, Arrays, Strings, and Primitives
This chapter assumes you already know how Object.keys, Object.values, and Object.entries behave on plain objects, and that you are comfortable with try...catch and the ?? operator. Here you will see what these methods do when the value you pass in is not a plain object. That happens more often than you might expect: an API response comes back as an array, a field holds null, or a function receives a string where it expected an object.
How the Methods Treat Non-Objects
All three methods start by converting their argument to an object. JavaScript calls this conversion ToObject. Most values convert without trouble, but null and undefined have no object form, so the conversion throws. Primitives such as numbers and strings are wrapped temporarily in Number or String objects, and the method then reads the wrapper's own enumerable string keys.
The full set of cases looks like this:
console.log(Object.keys(['x', 'y'])); // ['0', '1']
console.log(Object.entries('hi')); // [['0', 'h'], ['1', 'i']]
console.log(Object.keys(42)); // []
console.log(Object.values(true)); // []
try {
Object.keys(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}Arrays: Indexes Come Back as Strings
An array is an object whose indexes are property keys. Like all property keys, they are strings, so Object.keys returns '0', '1', and so on instead of numbers. If you do arithmetic with them, convert them first:
const letters = ['a', 'b', 'c'];
for (const key of Object.keys(letters)) {
console.log(key + 1, Number(key) + 1);
}
// 01 1
// 11 2
// 21 3Two more details catch people out. Holes in a sparse array are not properties, so they are skipped. Extra named properties added to an array are own enumerable properties, so they are included:
const sparse = ['a', , 'c'];
console.log(Object.keys(sparse)); // ['0', '2']
const tagged = ['a', 'b'];
tagged.label = 'pair';
console.log(Object.keys(tagged)); // ['0', '1', 'label']For a real array, for...of, forEach, or arr.entries() is usually the better choice. These give you numeric indexes and leave out non-index properties.
Strings and Other Primitives
A string's wrapper object has one own enumerable property per UTF-16 code unit, so you get indexes and characters. Characters outside the Basic Multilingual Plane, such as most emoji, take two code units and split into two separate entries:
console.log(Object.values('ok')); // ['o', 'k']
console.log(Object.keys('😀').length); // 2Numbers, booleans, symbols, and bigints convert to wrappers that have no own enumerable properties, so the result is always []. This fails quietly. A loop over Object.keys(42) runs zero times and raises no error.
Collections That Look Like Objects
A Map or Set stores its data internally, not as properties. Object.entries therefore returns an empty array:
const ages = new Map([['alice', 30], ['bob', 25]]);
console.log(Object.entries(ages)); // []
console.log([...ages.entries()]); // [['alice', 30], ['bob', 25]]To iterate a Map, use its own entries(), keys(), or values() methods, or loop over the Map directly with for...of.
Guarding Against null and undefined
When a value might be missing, fall back to an empty object before you iterate:
function countFields(record) {
return Object.keys(record ?? {}).length;
}
console.log(countFields({ a: 1, b: 2 })); // 2
console.log(countFields(null)); // 0
console.log(countFields(undefined)); // 0Summary Table
| Input | `Object.keys` result | Notes |
|---|---|---|
| `null`, `undefined` | Throws `TypeError` | Guard with `?? {}` |
| Array | Index strings plus extra named keys | Holes are skipped |
| String | Index strings | Emoji can take two indexes |
| Number, boolean, symbol, bigint | `[]` | No error is raised |
| `Map`, `Set` | `[]` | Use their own iterators |
Exercise
What does this code print, and why? const a = ['x', , 'z']; a.note = 'hi'; console.log(Object.entries(a));
Show answer
It prints [['0', 'x'], ['2', 'z'], ['note', 'hi']]. The hole at index 1 is not a property, so it is skipped. The index keys are strings. note is an own enumerable property, so it is included. Integer-like keys come first in ascending order, followed by note.
Exercise
A function calls Object.values(input).reduce((s, n) => s + n, 0). What does it return when input is 5, and what happens when input is undefined?
Show answer
For 5 it returns 0, because the Number wrapper has no own enumerable properties, so reduce starts from the initial value and has no elements to process. For undefined, Object.values throws a TypeError before reduce runs. Writing Object.values(input ?? {}) turns that case into 0 as well.