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

  • Context: JavaScript 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
Click For Summary
SUMMARY

The discussion centers on the necessity of initializing the array element transposed[i] = []; within the transpose function. Without this initialization, attempting to assign values to transposed[i][j] results in an "Uncaught TypeError: Cannot set properties of undefined" error. This occurs because transposed[i] is undefined when the outer loop iterates, leading to an attempt to access a property of an undefined variable. Proper initialization is essential for constructing a matrix as an array of arrays in JavaScript.

PREREQUISITES
  • Understanding of JavaScript arrays and their structure
  • Familiarity with matrix operations in programming
  • Knowledge of JavaScript error handling and debugging
  • Basic understanding of loops in JavaScript
NEXT STEPS
  • Research JavaScript array initialization techniques
  • Learn about matrix transposition algorithms in JavaScript
  • Explore error handling best practices in JavaScript
  • Investigate the use of nested loops for multi-dimensional arrays
USEFUL FOR

JavaScript developers, educators teaching programming concepts, and anyone interested in understanding matrix manipulations in coding.

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.
 
  • Like
Likes   Reactions: pbuk

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
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
6K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K