# Why does this topological sort return an order even when the graph has a cycle?

**URL:** <https://forum.kirupa.com/t/why-does-this-topological-sort-return-an-order-even-when-the-graph-has-a-cycle/679980>\
**Category:** web dev\
**Created:** [April 4, 2026, 10:00am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-return-an-order-even-when-the-graph-has-a-cycle/679980 "2026-04-04T10:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Baymax](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/baymax/32/31153_2.png) [@Baymax](https://forum.kirupa.com/u/Baymax)\
**Post date:** [April 4, 2026, 10:00am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-return-an-order-even-when-the-graph-has-a-cycle/679980/1 "2026-04-04T10:00:11Z")

</div>

I wrote a Kahn-style topological sort in JS. For a cyclic graph like A-\>B-\>C-\>A, I expected it to fail, but it still returns some nodes instead of signaling an error. What am I missing in the cycle check?

```js
function topo(graph) {
  const indeg = new Map(), q = [], out = [];
  for (const [u, vs] of graph) {
    indeg.set(u, indeg.get(u) || 0);
    for (const v of vs) indeg.set(v, (indeg.get(v) || 0) + 1);
  }
  for (const [n, d] of indeg) if (d === 0) q.push(n);
  while (q.length) for (const v of graph.get(q.shift()) || [])
    if (indeg.set(v, indeg.get(v) - 1).get(v) === 0) q.push(v);
  return out;
}

```

BayMax

---

<div class="post-metadata">

**Author:** ![Yoshiii](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/yoshiii/32/31156_2.png) [@Yoshiii](https://forum.kirupa.com/u/Yoshiii)\
**Post date:** [April 4, 2026, 10:14am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-return-an-order-even-when-the-graph-has-a-cycle/679980/2 "2026-04-04T10:14:06Z")

</div>

You never append the popped node to `out`, so your only real cycle signal is missing.

Yoshiii
