What is the standard format for assignment expressions?

I have the following function in JavaScript, and when I run it through JSLint, she yelled at me as I call it.

function getPos(event, element) { var x = event.clientX, y = event.clientY, currentElement = element; do { x -= currentElement.offsetLeft - currentElement.scrollLeft; y -= currentElement.offsetTop - currentElement.scrollTop; } while ((currentElement = currentElement.offsetParent)); return { x: x, y: y }; } 

In particular, an inline assignment expression in a while loop. I decided that double parentheses were the standard way of saying: "I expect the return value from the assignment expression to be assigned to the type for the conditional expression." JSLint does not seem to agree, even when I include assignment expressions. Then I tried to add !! ahead, and JSLint complains that it is "confusing use." So my question is, what is the proper way to format this?

EDIT: In "this" I was referring specifically to the expression inline assign. The purpose of my question was to clarify what an acceptable standard for this particular line was if someone really wanted to use this, and although I agree that the best answer to this question is the most correct way to write a function, this not the answer to the question I asked.

+7
javascript jslint standards
source share
2 answers

According to this article for JSHint, ESHint, and JSLint (since July 2013), you can force this condition as follows:

 do { // ... } while ((currentElement = currentElement.offsetParent) !== null); 

For more recent versions of JSLint, you're out of luck, and you need to separate your assignment if you rate all green.

+3
source share

It is better not to have assignment expressions in conditional expressions. But I believe that while is better for this case than do...while . You can convert the code to this

 function getPos(event, element) { var x = event.clientX, y = event.clientY, currentElement = element; while (currentElement) { x -= currentElement.offsetLeft - currentElement.scrollLeft; y -= currentElement.offsetTop - currentElement.scrollTop; currentElement = element.offsetParent; } return { x: x, y: y }; } 

Now there are no assignments in the conditional expression, and I think it looks clean.

+2
source share

All Articles