Chuckv Chuckv - 1 year ago 66
Javascript Question

Please interpret this java script line of code

Can someone interpret this javascript line for me?

mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',

Need to know what "?" does, and what 'DOMMouseScroll' : 'mousewheel', is saying particularly the "," at the end of the line... why isn't it a ";"

Thank you.

Answer Source

This is a ternary operator, used as a shorthand conditional statement:

it's the same as saying:

if ($.browser.mozilla) {
    mouseWheelEventName = 'DOMMouseScroll';
} else {
    mouseWheelEventName = 'mousewheel';

The first piece before the = is declaring a variable (mouseWheelEventName) dependent on the following condition.

The next piece between = the ? is the condition (is $.browser.mozilla true?).

Immediately after the ? is the then portion (if the condition is true, set the variable mouseWheelEventName to the string DOMMouseScroll).

After the : is the else (if the condition is NOT true, set the variable mouseWheelEventName to the string mousewheel).

Further reading:

As for why there is a comma at the end of it, we'd need to see a more complete code sample including what follows that to say for certain. If I had to guess, I would say the author of the code was chaining variable statements. This answer may shed some light for you: Javascript best practices, why to use comma to chain function/variable declarations? (see chosen answer)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download