My code return an error and I don’t understand why.
for (let i = 0; i < string.length; i++){
if(string[i].match(/a/)){
final += 1
} else if (string[i].match(/A/) && string[i - 1].match(/A/)){
final += 1
} else if (string[i].match(/A/)){
final += 2
}
}
else if (string[i].match(/A/) && string[i - 1].match(/A/)){
^
> TypeError: Cannot read properties of undefined (reading 'match')
> at typist (c:Users123DesktopJavaScriptLearningProjects27_06_2023.js:827:59)
> at Object.<anonymous> (c:Users123DesktopJavaScriptLearningProjects27_06_2023.js:837:13)
> at Module._compile (node:internal/modules/cjs/loader:1103:14)
> at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
> at Module.load (node:internal/modules/cjs/loader:981:32)
> at Function.Module._load (node:internal/modules/cjs/loader:822:12)
> at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
> at node:internal/main/run_main_module:17:47
2
Answers
string[i - 1]
givesundefined
at the start of the for loop wheni
is0
(string[-1]
).undefined
doesn’t have amatch
method thus the error:The error is occurring because string[i – 1] is undefined when i is 0. To fix the issue, start the loop from index 1: