Proposal: `Object.isEmpty(value)`

Isiah Meadows isiahmeadows at gmail.com
Thu Feb 14 06:31:24 UTC 2019


This would be roughly equivalent to `Object.keys(value).length === 0`,
but with a few exceptions:

1. If `value` is either `null` or `undefined`, it gracefully falls
back to `false` instead of throwing an error.
2. It takes enumerable symbols into account, like `Object.assign`.

So more accurately, it returns `false`  if the value is neither `null`
nor `undefined` and has an own, enumerable property, or `true`
otherwise.

It's something I sometimes use when dealing with object-based hash
maps (like what you get from JSON, input attributes). I typically fall
back to the (partially incorrect) `for ... in` with a `hasOwnProperty`
check for string keys, but I'd like to see this as a built-in.

There's also a performance benefit: engines could short-circuit this
for almost everything with almost no type checks. It's also an obvious
candidate to specialize for types.

- If it's not a reference type (object or function), return `true`.
- If it's not a proxy object, or a proxy object that doesn't define
`getPropertyDescriptor` or `ownKeys`, it's often just a memory load,
even with dictionary objects and arrays.
- If it's a proxy object with `ownKeys` and/or
`getOwnPropertyDescriptor`, this is the slow path, but you can still
short-circuit when `ownKeys` returns an empty array.

-----

Isiah Meadows
contact at isiahmeadows.com
www.isiahmeadows.com


More information about the es-discuss mailing list