webdad3
webdad3

Reputation: 9080

What is "(…) ? (…) : (…)" notation (three expressions delimited by question mark and colon) in JavaScript?

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

Upvotes: 23

Views: 30778

Answers (4)

Matt Huggins
Matt Huggins

Reputation: 83279

It's called a Conditional (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;
}

Upvotes: 32

BerggreenDK
BerggreenDK

Reputation: 5004

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.

Upvotes: 2

Alexander Gessler
Alexander Gessler

Reputation: 46607

It's the ternary conditional operator -- basically,

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

becomes

a = condition ? 4 : 5;

Upvotes: 13

Gumbo
Gumbo

Reputation: 655209

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.

Upvotes: 11

Related Questions