0
a = (a == b) ? c: b;

I don't understand. All of them {a, b, c} are variables set with certain value by the programmer.

Rehan Smith
  • 11
  • 1
  • 3
  • If **a** is equals to **b** then assigns **c** to **a** else **b**. – Gaston Flores Jun 27 '13 at 16:39
  • There's the same operator in other languages, but one thing to keep in mind with javascript, the conditional part of the ternary operator (the `(a == b)` in this example), is "truthy", not just simple booleans. So `99 ? "a" : "b"` will return "a", and `0 ? "a" : "b"` will return "b". This can let you do some cool stuff with this operator in javascript (just like you can with the `||` operator). – Joe Enos Jun 27 '13 at 16:41
  • if a is equal to be then a equals c , else a equals b . – Pbk1303 Jun 27 '13 at 16:41

7 Answers7

4

That is called the ternary operator: that is the same as doing:

if(a == b)
 a = c;
else
 a = b;
saamorim
  • 3,685
  • 15
  • 22
1

If a equals b then a = c otherwise a = b.

Jérôme
  • 1,979
  • 14
  • 21
1

This is a short form for an if and an assignment.

q = x ? y : z

q is the variable you assign to x is a boolean expression which will be true or false. If it is true y will be assigned to your variable q else z will be assigned to q.

Thor
  • 29
  • 6
0

This is the ternary operator, which is equivalent to:

if (a == b) {
  a = c;
} else {
  a = b;
}

The main difference is that if/else consists of conditional statements, while the ternary operator is a conditional expression. In other words, the ternary operator works as if the if/else were returning a value. In some other languages, if/else are expressions as well, so the following would be valid, and indeed equivalent to ?: :

a = (if (a == b) { c; } else { b; }) // not valid javascript

Be sure to check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

The Mozilla Developer Network is a fantastic reference for JavaScript.

Bruno Reis
  • 34,789
  • 11
  • 109
  • 148
0

if a equal to b then assign c to a , otherwise assign b to a

Instance Noodle
  • 217
  • 1
  • 10
0

In english -

If a is equal to b, then a = c. otherwise, a = b
ddavison
  • 25,442
  • 12
  • 70
  • 96
0

The ?: syntax is a ternary operator. Essentially it means that if a is equal to b than a equals c otherwise a equals b

Robert H
  • 10,659
  • 17
  • 63
  • 102