# Codewars diagonal-sum

trying to solve this:
Create a function that receives a (square) matrix and calculates the sum of both diagonals (main and secondary)

Matrix = array of `n` length whose elements are `n` length arrays of integers.

3x3 example:

``````diagonals( [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
] );

returns -> 30 // 1 + 5 + 9 + 3 + 5 + 7
``````

i’m trying first with the primary diagonal and it returns ‘01,2,34,5,67,8,9’
here my code:

``````function sum(matrix) {
var primary = 0;
for (var i = 0; i < matrix.length; i++)
{primary = primary + matrix[i,i];}

return primary;
}
``````

The problem lies here.
Inside property access brackets `matrix[ ...here...]` is an expression.
For example:

``````var array = [1, 2, 3, 4, 5, 6];
var value = array[5 - 2]; // array[3]
// value ===  array[3] === 4
``````

So when you try to access `matrix[i,i]` it will be treated as a serie of comma separated operands and it will evaluate to the final one.

If you want to access a value in a matrix (two dimensional array), you have to access the values like so:

``````primary = primary + matrix[i][i];
``````

Thanks a lot i will try again.

El El mar, 11 ago 2020 a las 14:31, Maciek Sitkowski via The freeCodeCamp Forum <freecodecamp@discoursemail.com> escribió: