Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot assign null to a variable

const letsMatch = (string, char) => {
  const newRegex = new RegExp(char, "gi");
  let result = string.match(newRegex);
  const findNegIndex = result.indexOf(char);
  if (findNegIndex === null) {
    return result = 0;
  } else {
    if (result.length === 2) {
    const findFirstIndex = fiveT.indexOf(char);
    const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1);
    result = findSecondIndex - findFirstIndex + 2;
    return result;
  } else {
    return (result = 0);
  }
  }
}

console.log(letsMatch('totititiTo', 'r'))

line 4: const findNegIndex = result.indexOf(char); Throws Uncaught TypeError: Cannot read properties of null (reading ‘indexOf’).

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

According to the documentation, String.prototype.match() will return null (not an empty array) when no matches are found.

And no matches are found.

You can default to an empty array when it returns null:

const letsMatch = (string, char) => {
  const newRegex = new RegExp(char, "gi");
  let result = string.match(newRegex) || []; // here
  const findNegIndex = result.indexOf(char);
  if (findNegIndex === null) {
    return result = 0;
  } else {
    if (result.length === 2) {
      const findFirstIndex = fiveT.indexOf(char);
      const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1);
      result = findSecondIndex - findFirstIndex + 2;
      return result;
    } else {
      return (result = 0);
    }
  }
}

console.log(letsMatch('totititiTo', 'r'))

(As an aside, it’s not really clear what this function is meant to accomplish, or what you expect return result = 0 to mean other than return 0. But at the very least the error is because you’re assuming string.match will always return an array, and there exists a use case where it does not.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading