Search code examples
javascriptnullish-coalescing

Javascript nullish coalescing returns "f { [native code] }"


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.


Solution

  • 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;