# Difference between using "let" in a "for" loop

#### marzooqahmed944

Hi, I was doing a determinant challenge on codewars when I encountered this issue. Apparently, my "for" loop for "i" was running only once when the matrix was 4x4 or bigger but it was running fine for a 3x3 matrix. But when I put "let" before "i", it worked for a matrix of any size (3x3 or bigger). I'm not an experienced JS programmer, so, I'd love it if someone could explain the difference and/or reason why my program was acting in this way.

--Code below--

//Buggy code
const determinant = (matrix) => {
if(matrix[0].length === 1) return matrix[0][0]
if(matrix[0].length === 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]))
sum = 0
for(i = 0; i < matrix[0].length; i++){
console.log(matrix, i)
subMat = []
for(j = 1; j < matrix.length; j++) {
subMat2 = []
for(k = 0; k < matrix[0].length; k++){
if(i === k) {}
else subMat2.push(matrix[j][k])
// else if(matrix[j][k] !== matrix[0])
}
console.log(subMat2)
subMat.push(subMat2)
}
if(i % 2 === 0) sum += matrix[0] * (determinant(subMat))
else sum += -(matrix[0] * (determinant(subMat)))
console.log(subMat, sum, matrix[0].length)
}
return sum
}

//Correct code
const determinantCorrected = (matrix) => {
if(matrix[0].length === 1) return matrix[0][0]
if(matrix[0].length === 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]))
sum = 0
for(let i = 0; i < matrix[0].length; i++){
console.log(matrix, i)
subMat = []
for(j = 1; j < matrix.length; j++) {
subMat2 = []
for(k = 0; k < matrix[0].length; k++){
if(i === k) {}
else subMat2.push(matrix[j][k])
// else if(matrix[j][k] !== matrix[0])
}
console.log(subMat2)
subMat.push(subMat2)
}
if(i % 2 === 0) sum += matrix[0] * (determinant(subMat))
else sum += -(matrix[0] * (determinant(subMat)))
console.log(subMat, sum, matrix[0].length)
}
return sum
}

//My test case
const matrix = [[ 1, 2, 3, 4, 5 ],
[ 5, 0, 2, 8, 3 ],
[ 3, 5, 6, 7, 1 ],
[ 2, 5, 3, 1, 2 ],
[ 1, 5, 6, 1, 2 ]]