27

While I was working on a project, I came across this snippet of code:

var params = JSON.parse(JSON.stringify(defaultParams));

Does this code actually do anything?

Mingwei Samuel
  • 2,917
  • 1
  • 30
  • 40
  • 4
    It can create a [simple clone of the object](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object). Note the [2nd answer](http://stackoverflow.com/a/5344074) by Corban Brook. – Jonathan Lonowski Jul 14 '14 at 19:39
  • 3
    It also validates that the object is serializable (it contains only primitives & no cycles). – tcooc Jul 14 '14 at 19:44

2 Answers2

32

It's a way of cloning an object, so that you get a complete copy that is unique but has the same properties as the cloned object.

var defaultParams = { a : 'b' };
var params = JSON.parse(JSON.stringify(defaultParams));

console.log( params.a ); // b
console.log( defaultParams.a ); // b
console.log( params === defaultParams ); // false

The above outputs false because even though both objects have the a property, with the value b, there are different objects that are independent of each other (they don't refer to the same reference).

The JSON method will only work with basic properties - no functions or methods.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • 5
    After years of using this "trick", I just realized - it messes up the date!! I got date property in output object in ISO format, as if I was invoking toISOString() method on it! – Dalibor May 08 '20 at 08:26
  • 3
    More cons of using this method of cloning given here: https://medium.com/@pmzubar/why-json-parse-json-stringify-is-a-bad-practice-to-clone-an-object-in-javascript-b28ac5e36521 It also messes up on NAN and Infinity. – DharmaTurtle Sep 14 '20 at 22:00
1

You can break the connection between two arrays.

For example:

const bulkAssignTreeView = JSON.stringify(this.bulkAssignTreeViewData);
this.bulkAssignTreeViewData = JSON.parse(bulkAssignTreeView);
robyaw
  • 2,274
  • 2
  • 22
  • 29
Behram Bazo
  • 230
  • 2
  • 6