JavaScript Need of transposed[i] = []; when we already have var transposed = []

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
Click For Summary
The discussion centers on the importance of initializing the `transposed[i]` array in the `transpose` function. When this line is commented out, it leads to a TypeError because `transposed[i]` is undefined, making it impossible to assign a value to `transposed[i][j]`. The need for this initialization is crucial as it sets up each row of the transposed matrix as an array, allowing the function to correctly store the transposed values. The conversation highlights the structure of a matrix as an array of arrays and emphasizes that without proper initialization, the code will fail to execute as intended.
shivajikobardan
Messages
637
Reaction score
54
TL;DR
codewars kata confusion
What's the need of the commented code here?

JavaScript:
function transpose(matrix) {
  var transposed = [],
  rows = matrix.length,
  cols = matrix[0].length;
  for (i = 0; i < cols; i++) {
    // transposed[i] = [];
    for (var j = 0; j < rows; j++) {
      transposed[i][j] = matrix[j][i];
    }
  }
  console.log(transposed);
}
transpose([[1, 2, 3], [4, 5, 6]])

When that part is commented, it throws an error:
Uncaught TypeError: Cannot set properties of undefined (setting '0')

I'm trying to understand the need of it. Because we've already initialized
var transposed = [],
 
Last edited by a moderator:
Technology news on Phys.org
Do you understand how a matrix here is constructed as an array of arrays? You can also look in the loop body and ask yourself whattransposed[i][j]is supposed to mean iftransposed[i]is undefined (this is what gives the error you mention).

Edit: Writing[i]here without the code block is tricky because that is also notation for italics in posts. Took a few tries to figure out what was going on.
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 12 ·
Replies
12
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
Replies
2
Views
5K
Replies
5
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K