I am trying to use a ternary operator to check if the value of an XML element is null. If it is then I want the variable to be one thing. If not then I would like it to return the value of element. This is what I have so far.
var rating = data.getElementsByTagName("overall_average")[0].childeNodes[0].length > 0 ? data.getElementsByTagName("overall_average")[0].childeNodes[0].nodeValue : "It is empty";
Ternary operator JavaScript is capable of turning a full-fledged if statement into a single line of code. The ternary operator JavaScript will assign a value to a variable if it satisfies a certain condition. Interestingly, it is the only operator that accepts 3 operands. You are already familiar with the if statement.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.
"the ternary operator returns always an rvalue. surprisingly it does" Do you meant "doesn't", as it can return lvalue (when both side are lvalues). In C, the conditional operator never yields an lvalue.
Here:
var node = data.getElementsByTagName( 'overall_average' )[0].childNodes[0];
var rating = node ? node.nodeValue : 'It is empty';
Note that this code throws (an error) in case there is not a single "overall_average" element in data
, so you might want to guard against that case if necessary...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With