1

I am trying to understand the Javascript/jQuery in this http://www.queness.com/post/12078/create-jquery-pinterest-pin-it-plugin plugin. The lines 20 and 22 are confusing me, the code is:

pi_media = e.data('media') ? e.data('media') : e[0].src,

pi_desc = e.attr('title') ? e.attr('title') : e.attr('alt'),

Can anyone help me out with what these lines mean in Javascript

Ankur
  • 50,282
  • 110
  • 242
  • 312
  • 2
    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator – j08691 Feb 10 '13 at 04:06
  • Sorry guys I don't know why I didn't see the exact duplicate. Feel free to close it. – Ankur Feb 10 '13 at 04:09
  • Just so you're aware, the colon `:` also has two other meanings aside from its use in the ternary operator, assignment within the context of an object literal, and declaration of a label. – Plynx Feb 10 '13 at 04:12
  • However the answers given on this page, seem more reference-like and higher quality, so perhaps there's value in keeping it open? – Ankur Feb 10 '13 at 04:12

4 Answers4

3

It's the JavaScript ternary operator.

x = condition ? a : b

is equivalent to

if(condition)
    x = a;
else
    x = b;

Note that an assignment is not necessary. As an expression, it simply evaluates and produces a or b depending on the truth value of condition.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
2

It's called the Ternary Operator. It means:

  • Evaluate the expression to the left of the ?
  • If the expression evaluated to true, run the first piece of code (between the ? and the :)
  • If the expression evaluated to false, run the second piece of code (after the :)

This is a construct common to many C-style languages.

Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
2

Those are part of the ternary operator.

Basically, if the condition before the ? is evaluated to true, the expression immediately following the ? is the one which is evaluated, and otherwise the expression following the : is evaluated.

jeff
  • 8,300
  • 2
  • 31
  • 43
1

For example take the code:
var result=condition?arg1:arg2;
First the condition is evaluated.
If the evaluation results to true, then arg1 is returned and assigned to result
If the evaluation results to false, then arg2 is returned and assigned to result

Govind Balaji
  • 639
  • 6
  • 17