What is "?:" notation in JavaScript?

webdad3 picture webdad3 · Jul 24, 2010 · Viewed 18.6k times · Source

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

Answer

Matt Huggins picture Matt Huggins · Jul 24, 2010

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;
}