0

I want to test weather array of custom type objects are empty or not . Here '?' is not checking empty and running the code and failing in case empty messageArray.

messageArray?.forEach((message: BannerMessage) => {
      const outPutMessageObj: OutPutMessage = this.getOutPutMessageObject(message);
      processedMessages.push(outPutMessageObj);
    });

The error i am getting is

Uncaught (in promise) TypeError: messageArray.forEach is not a function

Roster
  • 1,764
  • 6
  • 17
  • 36
  • 1
    You're using [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining), which has nothing to do with checking whether an array is empty, just whether a value (for instance, from a variable or property) is `null` or `undefined`. In the code shown, the optional chaining checks `messageArray` for `null` or `undefined` and shortcircuits if it is. To check if an array is empty, check its `length` property to see if it's `0`. – T.J. Crowder Feb 04 '22 at 10:48
  • 3
    I'm struggling with the question. If `messageArray` is an *empty array*, `forEach` will never call its callback and all will be well. If `messageArray` is `null` or `undefined`, the expression will short-circuit and the `forEach` callback will never be called, and all will be well. Only if `messageArray` is not `null` or `undefined` and (assuming it's an array) has elements in it will the callback be called. What's the actual problem here? – T.J. Crowder Feb 04 '22 at 10:53
  • 1
    I don't understand the phrase _"failing in case empty `messageArray`_" either. What is failing here exactly? Do you get some sort of error? – ruth Feb 04 '22 at 10:54
  • @T.J.Crowder Sorry myself not able reproduce the issue due to some server changes so got late to update the question. Can you please check now – Roster Feb 04 '22 at 13:50
  • The error message is telling you that although `messageArray` is not `null` or `undefined` (that would be a different error), `messageArray` doesn't have a `forEach` function, which suggests it's not an array. I'd put a breakpoint on that line and look at what it is. If you can't use a breakpoint, perhaps ```if (!messageArray.forEach) { throw new Error(`messageArray error: ${typeof messageArray}, ${Object.prototype.toString.call(messageArray)}`); }``` which will give you the (vague) type of what it is and then (for objects) something hopefully less vague (but a breakpoint would be better). – T.J. Crowder Feb 04 '22 at 13:58
  • (Also, FWIW, since it looks like TypeScript thinks it's an array (or at least something that has `forEach`, like a `NodeList`), it seems as though there's a type assertion or something gone awry regarding `messageArray`, or it would have warned you about this before the runtime error.) I hope you find it. Good luck! :-) – T.J. Crowder Feb 04 '22 at 14:03
  • 1
    Yes got it thank you @T.J.Crowder – Roster Feb 04 '22 at 14:43

0 Answers0