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

shivajikobardan
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:

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.