0

Possible Duplicate:
javascript ? : notation

what does the "?" operator mean?

Community
  • 1
  • 1
Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121

4 Answers4

3

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");

Femaref
  • 60,705
  • 7
  • 138
  • 176
bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • 1
    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 Sep 20 '10 at 00:28
  • 1
    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"); – bevacqua Sep 20 '10 at 00:32
1

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

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
1

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");
rebelliard
  • 9,592
  • 6
  • 47
  • 80
1

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.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    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 Sep 20 '10 at 00:37
  • 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 Sep 20 '10 at 18:25