tags:

views:

103

answers:

4

Possible Duplicate:
javascript ? : notation

what does the "?" operator mean?

+1  A: 

It, along with : comprises the ternary operator and is a shortcut for returning one of two values (the second and third sub-expressions), based on the result of the condition (the first sub-expression).

Wikipedia gives a good description: http://en.wikipedia.org/wiki/%3F:#Javascript

It's used like this:

var result = (condition ? value_for_true : value_for_false);

Example:

var result = (1 > 0 ? "It is greater" : "It is less");

The above example stores "It is greater" in the variable result.

On its own, ? does nothing except cause a syntax error when used without :.

SimpleCoder
@SimpleCoder - thanks, looked on google but it took the "?" to mean question.
Dirty Bird Design
Sure. It's a common feature in many languages by the way: http://en.wikipedia.org/wiki/%3F. Not just JavaScript.
SimpleCoder
+3  A: 

it means an inline if

condition ? true_statement : false_statement

e.g

if(condition){
alert("true");
}else{
alert("false");
}

is the same as condition ? alert("true"): alert("false");

Nico
For reference, the conditional operator's true and false parts should be values, not actions. I'd recommend `alert(condition ? "true" : "false")` instead -- though in this particular case, `alert(condition.toString())` may work as well. Either way, if you have to decide between two actions, use `if`/`else`; if you're deciding between two values, use `?:`
cHao
I was just showing that it can work just as a regular if, though you are right, it can be used like return (condition ? "ok" : "nope");
Nico
+1  A: 

It's part of the ternary operator.

// This simple if
if (25 > 23) {
    alert("yes");
} else {
    alert("no");
}

// Is the same as
alert(25 > 23 ? "yes" : "no");
Rafael Belliard
+1  A: 

You probably mean the ?:, or ternary, operator. Since this has been covered multiple times before, I'll refer you to this thread for a full explanation.

deceze
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
Ya know, people are gonna get rather confused if there ever ends up being another ternary operator. They won't know what to call the existing one anymore.
cHao