Javascript code meaning

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

Code:

`x=((next - present) == 356) ? 2 : (((present - last) == 382) ? 1 : 0);`
Could someone explain it for me.
• 12-07-2012, 03:58 AM
rdspoons
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.
• 12-07-2012, 06:15 AM
felgall
A longer version of the same code that does exactly the same thing using if statements instead of ternary operators is:

Code:

```if ((next - present) == 356) x = 2; else if ((present - last) == 382) x = 1; else x=  0;```
• 12-07-2012, 07:28 AM
Philip M
Quote:

Originally Posted by felgall
A longer version of the same code that does exactly the same thing using if statements instead of ternary operators is:

Code:

```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.
• 12-07-2012, 08:42 AM
felgall
Quote:

Originally Posted by Philip M
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.