tags:

views:

40

answers:

3
var p = this.getParams();
var pD = (o.params||{});
if (this.useJsonData) pD = (pD.jsonData||{});
this.cursor = (pD && pD[p.start]) ? pD[p.start] : 0;

And what is the difference between these two lines.

this.cursor = pD[p.start] || this.cursor || 0;

Is the first code fine or there is any fault in it.

A: 

The first one is a shortcut for an "if/else" statement. In detail, it means:

if(pD && pD[p.start])
   this.cursor = this.cursor;
else
   this.cursor = 0;

The second one is a boolean OR that delivers back True or False, and then this TRUE or FALSE gets assigned to this.cursor.

joni
Are you sure the second one delivers only FALSE? I thought OR operator would return TRUE if ANY element is TRUE ;)
Dies
That's not quite true. Simple test proves it.alert(1 || 0) yields 1 (which will evaluate to TRUE in a cond statement).
Sergei Tulentsev
aww sorry. it's early in the morning here
joni
here in Europe too :-)
Sergei Tulentsev
@Sergei I'm in Europe, too :D
joni
+1  A: 

Your second line has a fault. What if pD is null? Also it will keep value of this.cursor that is true (not null or false, that is).

Otherwise, they are identical.

Sergei Tulentsev
well, not necessarily identical. The first one always changes `this.cursor`, but the second one can potentially leave it unchanged.
Sean Hogan
That's what I wrote :-)
Sergei Tulentsev
Yup. Read twice, comment once.
Sean Hogan
A: 

Look at this page: https://developer.mozilla.org/en/JavaScript/Guide/Expressions_and_Operators

Search for conditional operator, logical operators and short-circuit evaluation.

Sean Hogan