Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a ternary operator to set a variable

Tags:

javascript

xml

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";
like image 353
Greg Wiley Avatar asked Jul 20 '12 20:07

Greg Wiley


People also ask

Can you assign a value to a variable within a ternary operator?

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.

How do you write 3 conditions in a ternary operator?

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.

How do you use a ternary operator example?

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.

Does the ?: ternary operator return a value How can I assign a value to the output of the ternary operator?

"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.


1 Answers

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...

like image 185
Šime Vidas Avatar answered Sep 30 '22 10:09

Šime Vidas