GFact | Why is Circular Reference BAD in JavaScript?
Last Updated :
06 Oct, 2023
Circular referencing is an idea when an object directly or indirectly refers to itself back. It creates a closed loop. Like other programming languages, JavaScript also faces this problem of circular referencing.
circular reference in javascript
Example:
JavaScript
var user = {
first_name: 'Geeks'
};
// Reference of user pointing to itself leading to circular reference
user.self = user;
console.log("The user:", user);
console.log("The user using self pointer:", user.self);
console.log("The user using double self pointer:", user.self.self); // Self referencing
OutputThe user: <ref *1> { first_name: 'Geeks', self: [Circular *1] }
The user using self pointer: <ref *1> { first_name: 'Geeks', self: [Circular *1] }
The user using double self pointer: <ref *1> { first_...
Why circular reference is bad ?
A circular reference occurs if two separate objects pass references to each other.
Older browsers especially IE6-7 were infamous for creating memory leaks as their garbage collector algorithm couldn’t handle couldn’t handle circular references between DOM objects and JavaScript objects. Sometimes faulty browser extensions might also be the cause of leaks. For example, FlashGot extension in firefox once created a memory leak.
However, from a pure design point of view, circular referencing is still a bad thing and a code smell. Circular referencing implies that the 2 objects referencing each other are tightly coupled and changes to one object may need changes in other as well.
How to Avoid circular references ?
There are a couple of ways you can solve this problem:
1) Use libraries
2) Implement a solution yourself.
3) Serialization : One major way to solve this is by using Serialization in JavaScript .
- This process involves serializing the object to remove some properties from an object before converting it to JSON.
- In this process, you can remove properties you are not interested in, or in our case, properties that can cause errors.
Below is the simple solution using serialization:
JavaScript
const obj = {};
obj.itself = obj
function replacer(key, value) {
if(key === 'itself') {
return null
}
return value
}
const stringified = JSON.stringify(obj, replacer)
console.log(stringified)
// {
// "name":"GeeksforGeeks",
// "isEncyclopedia":true,
// "features":["popular","encyclopedia"],
// "age":15,
// "products":{
// "first":"course",
// "second":"classes",
// "third":"content",
// "fourth":"Job portal"
// },
// "itself":null
// }
What we've done here is use the replacer argument of JSON. Stringify to modify the itself property.
In the replacer function, we check for the key itself, and return the value null for that key. This way, JSON. Stringify replaces the circular reference value with null during stringifying, thereby avoiding infinite stringification.
Similar Reads
Call by Value Vs Call by Reference in JavaScript Call by Value: In this method, values of actual parameters are copied to the functionâs formal parameters, and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. Suppose there is a varia
3 min read
Reference and Copy Variables in JavaScript In this article, we will talk about pass-by-value and pass-by-reference in JavaScript. JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, u
5 min read
Function that can be called only once in JavaScript In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer
3 min read
How to Find Circular References in Excel Circular Reference in Excel is like a loop that keeps going around in circles. It happens when a cell's formula depends on its own result, confusing Excel. In this article, you'll learn how to check, find, enable, or remove Find Circular References in Excel What is a Circular Reference in Excel?A ci
7 min read
Difference between Type Error and Reference Error in JavaScript JavaScript is one of the most popular programming languages in the world, and it is used by millions of developers to create dynamic and interactive web applications. However, like any programming language, JavaScript is not without its quirks and pitfalls. Two common issues that developers often en
6 min read
What is the practical use for a closure in JavaScript? In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned. The below examples show the practical use of closures: Example: In this example, a variable mult is defined that is local to the function
2 min read