Using a ternary operator to set a variable

I am trying to use the ternary operator to check if the value of an XML element is zero. If so, I want the variable to be one. If not, I would like it to return the value of the element. This is what I still have.

var rating = data.getElementsByTagName("overall_average")[0].childeNodes[0].length > 0 ? data.getElementsByTagName("overall_average")[0].childeNodes[0].nodeValue : "It is empty"; 
+6
source share
3 answers

The shortest way:

 var rating = (data.getElementsByTagName('overall_average')[0].childNodes[0] || {}).nodeValue || 'It is empty'; 
+5
source

Here:

 var node = data.getElementsByTagName( 'overall_average' )[0].childNodes[0]; var rating = node ? node.nodeValue : 'It is empty'; 

Please note that this code generates an (error) if there is not a single "total_average" element in the data , so you may need protection from this case, if necessary ...

+11
source

The triple operation looks wonderful to me. I would suggest (for readability and brevity) to define your overall_average object as a variable and refer to it after.

 var overall_average = data.getElementsByTagName("overall_average")[0].childeNodes[0]; var rating = overall_average.length > 0 ? overall_average.nodeValue : "It is empty"; 

Good luck

+1
source

Source: https://habr.com/ru/post/920994/


All Articles