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

add() unexpectedly mutates the original object. #955

Closed
ssoroka opened this issue Jul 26, 2013 · 4 comments
Closed

add() unexpectedly mutates the original object. #955

ssoroka opened this issue Jul 26, 2013 · 4 comments

Comments

@ssoroka
Copy link

ssoroka commented Jul 26, 2013

eg:

m = moment() # lets say it's Oct 3rd.
oct6 = m.add('days', 3)

oct6 is now oct 6th, as expected, but m has also changed, unexpectedly

oct7 = m.add('days', 4)

if add() had operated in a functional manner without mutating state, oct7 would in fact be set to october 7th, but because add() mutated the state of m, it's set to october 10th!

in fact, oct6 and oct7 are now the same object, m, and both reference october 10th.

this seems really unintuitive and can easily cause unintended consequences when moment objects are passed around in non-trivial applications.

@jgrocho
Copy link

jgrocho commented Jul 26, 2013

I got bit by this as well, until I read Moment Clone.

All moments are mutable.

Thus now I assume most methods will mutate the original object. I think both approaches are valid, but mutation at least matches the original Date API which mutates objects.

You have to call moment#clone on the moment or wrap it in a call to moment like

m = moment() # let's say it's Oct 3rd.
oct6 = m.clone().add('days', 3)
oct7 = moment(m).add('days', 4)

@ichernev
Copy link
Contributor

This is not a bug, its a feature! Read a discussion here: #390

It don't think this is ever going to change, at least because of compatibility issues.

@akenverus
Copy link

This is not a bug, its a feature! Read a discussion here: #390

It don't think this is ever going to change, at least because of compatibility issues.

This feature sucks.

@KristjanESPERANTO
Copy link

@akenverus As moment is no longer being actively developed, it is advisable to switch your projects to another library.

https://momentjs.com/docs/#/-project-status/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants