
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why circular reference is bad in javascript?
A circular reference occurs if two separate objects pass references to each other.
In older browsers circular references were a cause of memory leaks. With improvements in Garbage collection algorithms, which can now handle cycles and cyclic dependencies fine, this is no longer an issue.
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.
Avoiding circular references
There is no one way to avoid circular reference in JS. It depends on the use case and the situation and may also be necessary in some cases. We can take an example to understand this:
Suppose you have 2 objects, Dog and Person. You want to be able to reference the owner of a dog just using the dog object and the pet of a person using the person object.
let dog = new Dog(); let person = new Person(); // Creating a circular reference dog.owner = person person.pet = dog
In most scenarios you'll need to access only one object and derive the other from it. so you can break one of the links. If not then you can use a map to map objects in the reverse scenario. But instead of using hacks, it is better to let the circular ref be there.
- Related Questions & Answers
- Example of a circular reference in Javascript
- How to avoid circular reference in OOP Javascript?
- Why is using the JavaScript eval() function a bad idea?
- Why are "continue" statements bad in JavaScript?
- Why combination of twitter and facebook is bad
- Why importing star is a bad idea in python
- Why do you think privatization of education is bad?
- Why is it bad to watch TV while eating?
- Why eating the raw food is bad for health?
- Why are women considered bad drivers?
- Why is using “for…in” loop in JavaScript array iteration a bad idea?
- Why is using “for…in” with array iteration a bad idea in javascript?
- Why are global variables bad in C/C++?
- Why film stars make bad leaders in India?
- Why do I sweat too much, Is it bad for me?