There is one thing that really irks me in Javascript, everything is passed by reference. Recently in a project I was working on, I had an object of widget options I needed to modify. I also needed to offer the ability to revert the changes made to this object.
The kicker is: this object is complex. It isn’t just properties and values, it has other objects inside of it and arrays. Everyone has an opinion on how you should do it, many ways to skin a cat so-to-speak.
I tried some of the various deep merge and clone methods out there, tried Lodash and the solution I ended up going with is:
var clonedWidget = (JSON.parse(JSON.stringify(originalWidget)));
The beautiful thing about this approach is that it can take an object with infinite levels of nesting, turns it into a string that represents JSON and then we parse the string to get back JSON, thus giving us a new object.
While there is a slight performance hit for large objects, it will not be noticeable unless you’re profiling your code on a low-level that most do not bother going to. This is the most straightforward and easy-to-use solution that has great performance and works great.
There could be issues with this approach that I have yet to run into. So, like all code you find on the Internet, don’t just blindly copy and paste without doing some testing first. Just because it works for me, does not mean it will work for you.