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.
 
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

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