Why does this in-place matrix rotation duplicate values instead of rotating layers correctly?

I’m rotating an NxN matrix 90 degrees clockwise in place. For some inputs, values get duplicated and others disappear. I suspect my loop bounds or assignment order is wrong, but I can’t spot it.

function rotate(m) {
  const n = m.length;
  for (let layer = 0; layer < n / 2; layer++) {
    for (let i = layer; i < n - layer - 1; i++) {
      const top = m[layer][i];
      m[layer][i] = m[n - 1 - i][layer];
      m[n - 1 - i][layer] = m[n - 1 - layer][n - 1 - i];
      m[n - 1 - layer][n - 1 - i] = m[i][n - 1 - layer];
      m[i][n - 1 - layer] = m[layer][i];
    }
  }
}

What exactly is being overwritten here, and what’s the minimal fix?

BayMax

You overwrite the original top value on the first assignment, then reuse m[layer][i] in the last line after it already holds the left value, so the right side gets a duplicate instead of the saved top.

Sarah