0

what is "?" in "instances?.map" doing here. I thought it was checking for instances to be non-null before executing map on it. If it is what might be the reason for this error? enter image description here

aryan singh
  • 374
  • 2
  • 9
  • See: [Optional Chaining](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwj6-ubx99HzAhWRsRQKHSM8AhAQFnoECAUQAQ&url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FReference%2FOperators%2FOptional_chaining&usg=AOvVaw3fLcEvZqB0O4DQx47AqDMT) – Yousaf Oct 17 '21 at 17:09

2 Answers2

1

Your understanding of .? is correct.

(With code likex.y you call . the "chaining operator".

With x?.y you call ?. the "optinal chaining operator" meaning that if x is nullish it will bail and not run the map fn)

The error is unrelated to the optional chaining. you would've got the same error if you used normal chaining. The error is likely that instances is NOT actually an Array so lacks the map function.

instances might be some kind of "Array-like object".

(Like a list of Promises. Or a NodeList. For example: document.querySelectorAll("a") returns a NodeList which is ...kinda lika an array but not exactly, it lacks a map function. So you need to convert it to an Array first if you wanna map.

Example: This throws an error because the return object lacks a map fn: document.querySelectorAll("a").map(link => link.innerHTML)

This works because the return object has a map fn: Array.from(document.querySelectorAll("a")).map(link => link.innerHTML)

Drkawashima
  • 8,837
  • 5
  • 41
  • 52
0

The error does not say that instances is null, it says that it does not have a .map function.

You should check where it is declared and what it contains. It looks like an object, you cannot use .map on an object like that but it has to be an array.

Balastrong
  • 4,336
  • 2
  • 12
  • 31