0

Moment.js mentions that the data is mutable here and therefore if you say:

var a = moment('2016-01-01'); 
var b = a.add(1, 'week'); 
a.format();
"2016-01-08T00:00:00-06:00"

The data in a changed when naively changing b without the use of .clone()

In the process of debugging I am uncertain whether bugs are caused by the logic of my code or by the data getting changed. As a result I have been spamming .clone() everywhere which decreases readability.

Is there a list of methods that mutate the data in moment.js?

Examples:

  • It is safe to assume methods such as .add, .subtract
  • how about other methods such as .diff?
  • how about the equals operator on two moments?

Is there list of such methods? The docs are really good at showing what the code can do but I am having trouble finding what the code does do.

Kevin Crum
  • 195
  • 2
  • 16

2 Answers2

2

You can use this plugin and avoid spamming the clone method. In generally, data mutates in moment.js and it generally creates bugs.

1

Firstly, I would presume that all methods listed in the MomentJS doc under the category of Manipulate and all setters will mutate your date.

Meanwhile, other methods and getters will not mutate your date. That will be the first rule that I will be using. When in doubt, use jsFiddle to perform a quick test to certify that there are no mutations involved.

tctham
  • 213
  • 2
  • 9