-2

I am getting an unexpected result while trying to use nullish coalescing operator on a return value that might be an array or might have an array as a child

  const storedKeys = await getStoreKeys();

  let keys = storedKeys.keys ?? storedKeys;
  console.log(keys);

console.log output:

ƒ keys() { [native code] }

Any idea on what might be going wrong? Thanks.

Aastha Bist
  • 324
  • 2
  • 11
  • 1
    Can you post the code for `getStoreKeys`? – chazsolo Aug 22 '22 at 18:31
  • 1
    If `storedKeys` is an array, then `keys` is the array method that returns an iterator of its keys, or rather, indices, because it's an array. – kelsny Aug 22 '22 at 18:33
  • @kelly, I think you mean if storedKeys is an Object or Map type. May be try invoking `storedKeys.keys()` with braces – MWaheed Aug 22 '22 at 18:37
  • 1
    @MWaheed Arrays are objects, and thus they have a `keys` method as well. – kelsny Aug 22 '22 at 18:38
  • Object has no "keys" method, at least not directly. Sure you can do Object.keys(someObj) but you can't do someObj.keys (undefined). – James Aug 22 '22 at 18:42
  • 1
    Array has [`keys`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys?retiredLocale=uk) method, which logs into console – Mike Aug 22 '22 at 18:48
  • Why do you think nullish coalescing has anything to do with this? – Ruan Mendes Aug 22 '22 at 19:00

1 Answers1

1

if storedObject is an array, it has a built-in keys() method (storedObject.keys() is equivalent to Object.keys(storedObject)). So the property isn't null, and it returns this function.

Use a ternary that checks if it's an array:

const storedKeys = Array.isArray(storedObject) ? storedObject : storedObject.keys;
Barmar
  • 741,623
  • 53
  • 500
  • 612