...

View Full Version : Javascript code meaning



Philosophaie
12-07-2012, 03:56 AM
I am having trouble with the meaning of this piece of Javascript code:


x=((next - present) == 356) ? 2 : (((present - last) == 382) ? 1 : 0);

Could someone explain it for me.

rdspoons
12-07-2012, 04:58 AM
x=((next - present) == 356) ? 2 : (((present - last) == 382) ? 1 : 0);


next present and last are to hold numeric values

the JavaScript ternary operator is used to assign a value to x
x = (comparison_that_resolves_to_true_or_false)? value_returned_if_true : value_returned_if_false;

In your code provided x is assigned the value 2 if next is greater than present by exactly 356.
If next is any other value, x is assigned the value 1 if present is greater than last by exactly 382.
If present is any other value, x is assigned the value of 0.

in other words,

x is assigned the value 2 if next-present equals 356.
if next-present does not equal 356 then
x is assigned the value 1 if present-last equals 382.
if present-last does not equal 382 then
x is assigned the value 0.

felgall
12-07-2012, 07:15 AM
A longer version of the same code that does exactly the same thing using if statements instead of ternary operators is:


if ((next - present) == 356) x = 2;
else if ((present - last) == 382) x = 1;
else x= 0;

Philip M
12-07-2012, 08:28 AM
A longer version of the same code that does exactly the same thing using if statements instead of ternary operators is:


if ((next - present) == 356) x = 2;
else if ((present - last) == 382) x = 1;
else x= 0;

Longer, but much clearer. Doubt if there is any discernable speed difference.

felgall
12-07-2012, 09:42 AM
Doubt if there is any discernable speed difference.

In terms of execution time I would guess that if you ran a few billion iterations that the speed difference might just about become large enough to measure in milliseconds.

I haven't actually counted the number of ternary references in jQuery but their use there possibly saves Gigabytes a month of bandwidth on the servers delivering copies of the library to the hundreds of millions of people visiting pages that use that library - making it well worth the trouble of using them as much as possible in place of if statements for that library. Individuals viewing the pages still wouldn't notice any significant difference in load times though.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum