skip to Main Content

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


  1. string[i - 1] gives undefined at the start of the for loop when i is 0 (string[-1]).

    undefined doesn’t have a match method thus the error:

    TypeError: Cannot read properties of undefined (reading 'match') at
    
    Login or Signup to reply.
  2. The error is occurring because string[i – 1] is undefined when i is 0. To fix the issue, start the loop from index 1:

      for (let i = 1; i < string.length; i++){
        if (string[i].match(/a/i)){
            final += 1;
        } else if (string[i].match(/A/i) && string[i - 1].match(/A/i)){
            final += 1;
        } else if (string[i].match(/A/i)){
            final += 2;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search