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

  • JavaScript
  • Thread starter shivajikobardan
  • Start date
In summary, the commented code in the given function is necessary because it initializes the transposed array, which is used to store the transposed matrix. Without this initialization, the transposed array would be undefined and attempting to set properties on it would result in an error. This code also helps to construct the matrix as an array of arrays.
  • #1
shivajikobardan
674
54
TL;DR Summary
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
  • #2
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.
 
  • Like
Likes pbuk

Similar threads

  • Programming and Computer Science
Replies
15
Views
3K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
Replies
5
Views
1K
Replies
5
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
2
Views
5K
Back
Top