JavaScript Ternary Operator does not work when the first condition runs through else branch

I got this line of code here.

 text={image.alt + " " + (uniqueLight.includes(image.id) ? uniqueLight.indexOf(image.id) : uniquePlug.indexOf(image.id))}

The third part of the text which is the ternary part, basically counts the number of elements I selected. As you can see, the conditional branch starts with uniqueLight and if I initally select an element from uniqueLight , it does not give any error and works well.

Light choosen first

But if I select an element from uniquePlug initally, it does not work.
You can see the error in the console

And if I swipe the uniqueLight with uniquePlug, and vice versa, the opposite occasion occurs.

How can I fix this or write that line of code properly?

>Solution :

You can use the optional chaining operator (?)

uniqueLight?.includes(image.id)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Leave a Reply