Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
Why doesn't Map have circular reference issue but normal object does in JavaScript?

I tried to solve an algo question using JavaScript and got circular reference error, I can understand that because I use objects as the keys in the visited object, and since it's an unidirectional graph so it will have circular references. However, after I replaced the object with Map, I got the problem solved.

I read some docs on MDN but still couldn't understand how Map solves the circular reference issue under the hood. Can anyone shed me some lights on this?

Here's my code using normal object that caused circular reference error:

/**
 * // Definition for a Node.
 * function Node(val, neighbors) {
 *    this.val = val === undefined ? 0 : val;
 *    this.neighbors = neighbors === undefined ? [] : neighbors;
 * };
 */

/**
 * @param {Node} node
 * @return {Node}
 */
var cloneGraph = function(node) {
  if(!node){
    return node;
  }

  const clone = new Node(node.val);
  const queue = [node];
  const visited = {node: clone};
  
  while(queue.length){
    let n = queue.shift();

    for(let i of n.neighbors){
      if(!(i in visited)){
        queue.push(i);
        visited[i] = new Node(i.val);      
      }
      
      visited[n].neighbors.push(visited[i]);
    }
  }

  return visited[node];
};

The output I got from printing the visited[node]:

{
  node: { val: 1, neighbors: [] },
  '[object Object]': <ref *1> {
    val: 2,
    neighbors: [ [Circular *1], [Circular *1], [Circular *1], [Circular *1] ]
  }
}

And here's the code used Map and passed:

var cloneGraph = function(node) {
  if(!node){
    return node;
  }

  const clone = new Node(node.val);
  const queue = [node];
  const visited = new Map();
  visited.set(node, clone);
  
  while(queue.length){
    let n = queue.shift();

    for(let i of n.neighbors){
      if(!visited.has(i)){
        queue.push(i);
        visited.set(i, new Node(i.val));  
      }
      
      visited.get(n).neighbors.push(visited.get(i));
    }
  }

  return visited.get(node);
};

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!