How do I work around mutability in moment.js?

Shengbo1618 picture Shengbo1618 · Jun 22, 2015 · Viewed 41.1k times · Source

I've run into a problem where I have to store the initial values of a moment object but I'm having some trouble preventing my variable from changing along with the original object.

Unfortunately Object.freeze() doesn't work, because moment.js returns an "Invalid date" error when I try to format that.

Answer

razorbeard picture razorbeard · Jun 22, 2015

There's a Moment.js plugin on NPM called frozen-moment - You could use moment().freeze() in place of Object.freeze(moment()).

Otherwise, vanilla Moment.js has a clone method that should help you avoid mutability problems, so you could do something like this:

var a = moment(),
    b = a.clone(); // or moment(a)

UPDATE:

It has been two years since I wrote this answer. In this time, another library for working with dates has surfaced and gained a lot of traction: https://date-fns.org/

This library is immutable by default and follows a modular, functional architecture, which means it is better suited to tree shaking and client-side bundling. If you are working on a project that makes extensive use of Webpack on the client side, and find that Moment.js is giving you trouble with your build, or even if Moment.js' mutability is causing you a lot of headache, then you should give date-fns a try.