Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda