0

I came across some code on an MDN article, and I'm not really sure how to make sense of what it does.

document.onmousemove = function(e) {
  curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
  curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}

I'm familiar with ternary operators, but I've never seen multiple "?" used in one line. Can someone explain to me how to evaluate the code for curX and curY? I would appreciate a simple explanation as I'm fairly new, but be as detailed as you want. Thanks

embracethefuture
  • 515
  • 7
  • 17
  • It's just two ternarys per line – j08691 Jan 15 '21 at 16:22
  • It does the same thing - `a ? b : c` evaluates to `b` if `a` is truth-y, otherwise `c`. This is an expression, so can be used in another expression e.g. `a ? b : c ? d ? e : f : g ? h : i`; the parentheses just help with readability – jonrsharpe Jan 15 '21 at 16:22
  • 1
    It is a basically like a nested if – Aalexander Jan 15 '21 at 16:22
  • 1
    It is essentially a nested `if...else if...else` statement. Nested ternaries can be pretty challenging to read, so frequently linters will flag them; it trades readability for conciseness. – Alexander Nied Jan 15 '21 at 16:23
  • 1
    It's just a nested conditional operator.¹ If `window.Event` is truthy, `e.pageX` is assigned to `curX`. Otherwise, the result of `e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)` is assigned to `curX`. That again involves using the conditional operator to pick between `documentElement` and `body`. (¹ The conditional operator is **a** ternary operator [an operator accepting three operands], and it's the only one in JavaScript **for now**, but it may not be forever. The proper name of `? :` is the *conditional* operator.) – T.J. Crowder Jan 15 '21 at 16:23
  • @jonrsharpe how do you even read the expression you wrote? Is it from left to right? I'm confused – embracethefuture Jan 15 '21 at 16:24
  • Well exactly, that's why it's better to include parentheses! – jonrsharpe Jan 15 '21 at 16:24
  • 1
    https://stackoverflow.com/q/38875471/3001761 – jonrsharpe Jan 15 '21 at 16:29

0 Answers0