thundermittens
thundermittens

Reputation: 3

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').

Upvotes: 0

Views: 623

Answers (2)

David
David

Reputation: 219127

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.)

Upvotes: 1

Count Spatula
Count Spatula

Reputation: 104

Depending on what you're coding in...

Use ?. - it'll return undefined if result doesn't have that property, and the || will shunt it on over to the null const findNegIndex = result?.indexOf(char) || null;

or

const findNegIndex = result ? result.indexOf(char) : null;

I'd also shy away from a variable named "string", for readability's sake - since String.match

Upvotes: 0

Related Questions