Aha! null is an object that isn't an Object!
var x = null; if (typeof x == 'object') print(Object.keys(x).join(', '));
parent
bd61ccb2
No related branches found
No related tags found
-
Many truthy things can be non-objects, so testing for thruthiness isn't useful. The test is there specifically to find things that can be passed to Object.keys() without an exception.
The else case is an implied return... expanding to something like:
if (typeof obj !== 'object') return if (obj === null) return
would be needlessly verbose.
I generally prefer a single return as a pattern except in cases where indentation gets too deep or when goto would be required. Hunting for returns when debugging is a PITA.
-
Anything that is truthy (and some that aren't, like
false
) can be passed to Object.keys() .. so that's the only check that is needed.> Object.keys(true) [] > Object.keys(1) [] > Object.keys(new Date()) [] > Object.keys(false) [] > Object.keys([]) []
For that matter, you could just omit the check, and use
Object.keys(Object(obj))
which will work for anything, includingnull
.
Please register or sign in to comment