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

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

Why do we need to set transposed[i] to an empty array if we already have var transposed = []?

Setting transposed[i] to an empty array ensures that each index in the transposed array is also an array, allowing us to store values in a two-dimensional format.

What happens if we don't initialize transposed[i] as an empty array?

If we don't initialize transposed[i] as an empty array, trying to access or modify transposed[i] will result in an error since it will be undefined.

Can we achieve the same result without setting transposed[i] to an empty array?

No, in order to store values in a two-dimensional array format, we need to initialize each index in the transposed array as an empty array.

Is there a more efficient way to initialize transposed[i] as an empty array?

One alternative method is to use a loop to iterate through the desired length and set each index of transposed to an empty array.

What is the purpose of using transposed[i] = [] instead of just leaving it as undefined?

By setting transposed[i] to an empty array, we ensure that each index is defined and can be accessed or modified without causing errors in our code.

Similar threads

Back
Top