Skip to content

Instantly share code, notes, and snippets.

@alexserver
Created January 27, 2015 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexserver/971fb8c1682aa5003942 to your computer and use it in GitHub Desktop.
Save alexserver/971fb8c1682aa5003942 to your computer and use it in GitHub Desktop.
Circular Reference in Javascript, and how to avoid it.
//https://www.npmjs.com/package/json-stringify-safe
var stringify = require("json-stringify-safe");
var a = {
type: "Son",
name: "John"
};
var b = {
type: "father",
name: "Michael"
};
var c = {
type: "grandpa",
name: "Elias"
};
a.father = b;
a.grandpa = c;
b.son = a;
b.father = c;
c. grandson = a;
c.son = b;
try {
//Will lead to circular reference while printing in console
console.log("Son ", a);
//Will lead to error because of the endless conversion
console.log("Son JSON Parsed ", JSON.stringify(a));
}
catch (ex) {
console.log("Error >> ", ex);
}
finally {
//this needs to happen in finally, because of previous conversion.
//Will print safe parsed JSON string
console.log("Son Safe Parsed ", stringify(a));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment