Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "?:" notation 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).

like image 203
webdad3 Avatar asked Jul 23 '10 22:07

webdad3


People also ask

What is the notation in JavaScript?

JavaScript provides two notations for accessing object properties. The first, and most common, is known as dot notation. Under dot notation, a property is accessed by giving the host object's name, followed by a period (or dot), followed by the property name.

What does >>> mean in JavaScript?

The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.

What is dot operator in JS?

The dot (.) is simply an operator that sits between its operands, just like + and -. By convention, the variables stored in an object that we access via the dot operator are generically called properties. Properties that happen to be functions are called methods.

What is dot notation syntax?

Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.


2 Answers

It's the ternary conditional operator -- basically,

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

becomes

a = condition ? 4 : 5;
like image 30
Alexander Gessler Avatar answered Oct 01 '22 23:10

Alexander Gessler


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;
}
like image 110
Matt Huggins Avatar answered Oct 01 '22 21:10

Matt Huggins