Which fix removes the bug?
function keysOf(v) {
if (typeof v === 'object') return Object.keys(v);
return [];
}
keysOf(null); // TypeError
- Write
typeof v == 'object' - Also require
v !== null - Use
Object.entries(v)instead - Check
typeof v !== 'undefined'
typeof null is 'object' (a historic quirk), so null passes the check and Object.keys(null) throws. Rule null out explicitly.
Play Problem Solving ▸