Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading