0

This problem is from code signal and I solved it, The first solution entered worked but I want to know why the second doesn´t.

I am supposed to write a function that takes a matrix as an input and returns a sum of items that are not below a 0.

Here is an example of the matrix.

matrix = [[1, 1, 1, 0], 
          [0, 5, 0, 1], 
          [2, 1, 3, 10]]

the output should be solution(matrix) = 9

    function solution(matrix) {
    let sum =0  
    for(j=0;j<matrix[0].length;j++){
    for(let i=0;i<matrix.length;i++){
    if(matrix[i][j]==0){
    break
    }
    else{ 
    sum += matrix[i][j]
    }
    }
    }
    return sum
    }

this works but this other one has an error

    function solution(matrix) {
    let sum =0
    for(j=0;j<matrix[j].length;j++){
    for(let i=0;i<matrix.length;i++){
    if(matrix[i][j]==0){
    break
    }
    else{ 
    sum += matrix[i][j]
    }
    }
    }
    return sum
}
    Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at solution (<anonymous>:5:25)
    at <anonymous>:1:13

The problem is using the the variable as an index for the columns

I just want to know why the later did not work in order to learn

od507
  • 1
  • 2

1 Answers1

0

As you noticed, the key difference is how the for loop is intiailized:

for (j = 0; j < matrix[0].length; j++)

vs

for (j = 0; j < matrix[j].length; j++)

The order of execution in a for loop is:

  • Start at j = 0
  • check j < matrix[j].length. If the statement evaluates to true, execute the block between {...}
  • increment using j++

When j = 3, matrix[j].length = 4 and the block executes, followed by j++.

Now j = 4, but matrix[j] does not exist (undefined), and hence the error Cannot read properties of undefined (reading 'length').

You may find this useful: What is the exact order of execution of Javascript's for loop?

mani
  • 3,068
  • 2
  • 14
  • 25