views:

163

answers:

5

This is probably a dumb question, but... I found this snippet of code in my travels in researching JSON:

var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

I'm seeing more and more of the ? and : notation. I don't even know what it is called to look it up! Can anyone point me to a good resource for this? (btw - I know what != means).

Thanks!

+13  A: 

It's called a ternary operator. It's essentially a condensed if-else.

So this:

var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

...is the same as this:

var array;
if (typeof objArray != 'object') {
    array = JSON.parse(objArray);
} else {
    array = objArray;
}
Matt Huggins
Actually it is CALLED a conditional operator, but it IS A ternary operator. A ternary operator is any operation that takes 3 inputs. In many contexts, however, ternary operator has become synonymous with conditional since the conditional is either the most famous or sometimes the only ternary operator present in that language. For example, ++ -- are called unary operators, and + - / are called binary operators, etc.But that's just semantics, good answer, plus 1. :)
Razor Storm
@Razor – Nice addition; also have a look at the ECMAScript 5 specification of the [Conditional Operator ( ? : )](http://ecma262-5.com/ELS5_Section_11.htm#Section_11.12).
Marcel Korpel
Learned something new, thanks Razor!
Matt Huggins
@Razor - +1 for your comment, and [according to the MDC](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Conditional_Operator) the conditional operator is the only ternary operator in Javascript.
Peter Ajtai
+5  A: 

That’s called the conditional operator:

condition ? expr1 : expr2

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

Gumbo
+1 for naming the only ternary operator in Javascript correctly.
Peter Ajtai
+8  A: 

It's the ternary conditional operator -- basically,

if (condition) {
   a = 4;
}
else {
   a = 5;
}

becomes

a = condition ? 4 : 5;
Alexander Gessler
Like Razor pointer out in the accepted answer: It's actually the [JS conditional operator](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Conditional_Operator), which is the only ternary operator in JS.
Peter Ajtai
+1  A: 

Just read it like this:

result = (condition) ? (true value) : (false value);

place what ever you like in the 3 operators.

As many has compared it to an IF.. THEN structure, so it is.

BerggreenDK
A: 

The same thing, but probably faster:

result = condition && 'true' || 'false'
eduardocereto
Not necessarilly faster, but way *less* obvious and maintainable.
JaredReisinger
Also not an answer, you should write this as a comment.
Razor Storm