Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

momentJS var 'not modified' in while loop #770

Closed
benjaminhoffman opened this issue Feb 1, 2017 · 3 comments

Comments

@benjaminhoffman
Copy link

commented Feb 1, 2017

Noticed that linter yells that my while-loop variable "is not modified in this loop", even though I am (via momentJS). You'll see from the code & screenshot below that I subtract one month with momentJS on each iteration. Here's the relevant part:

    const dateStart = moment('2016-02-01')
    const dateEnd = moment()
    while (dateStart < dateEnd) {
      //
      //subtract 1mnth
      dateEnd.subtract(1, 'month')
    }

Thoughts on this one?

@feross

This comment has been minimized.

Copy link
Member

commented Feb 2, 2017

This is a limitation of the no-unmodified-loop-condition rule. More info about it here: eslint/eslint#6984

In short, what's happening is that the identity of the dateEnd object isn't actually changing in the loop body, as the subtract method just makes some changes to an internal Date object. But when the condition is executed, it is implicitly being coerced to a Number, which is of course different each time through the loop.

So, you can work around this rule by explicitly calling valueOf():

while (dateStart.valueOf() < dateEnd.valueOf()) {
}

(You could also use d.unix() or d.toDate())

@feross feross closed this Feb 2, 2017

@feross

This comment has been minimized.

Copy link
Member

commented Feb 3, 2017

There is a proposal to eslint that would let us relax this rule a bit so that any reference to the condition variables in the loop body would be treated as a modification. Then it would only be an error to completely omit a condition variable from the body.

You can follow this here: eslint/eslint#8021

@dcousens

This comment has been minimized.

Copy link
Member

commented Feb 3, 2017

it is implicitly being coerced to a Number

I always found the nature of Dates doing that really funky and weird

@lock lock bot locked as resolved and limited conversation to collaborators May 10, 2018

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
3 participants
You can’t perform that action at this time.