MediumModern JS🐛 Debug Challenge

Regex with global flag alternates true/false

Buggy Code — Can you spot the issue?

const emailRegex = /^\w+@\w+\.\w+$/gi;

function isValid(email) {
  return emailRegex.test(email);
}

console.log(isValid('a@b.com'));
console.log(isValid('a@b.com'));

Fixed Code

const emailRegex = /^\w+@\w+\.\w+$/i;

function isValid(email) {
  return emailRegex.test(email);
}

console.log(isValid('a@b.com'));
console.log(isValid('a@b.com'));

Bug Explained

Bug: With the g flag, regex.test() advances lastIndex after a match. The next call starts from the advanced position — past the string end — returns false and resets to 0.

Explanation: Removing g makes the regex stateless — always starts from position 0. g is only needed when finding multiple matches with exec() in a loop.

Key Insight: The g flag makes regex stateful via lastIndex. Never use g for simple test() checks — it alternates true/false. Remove g or reset lastIndex = 0.

More Modern JS Debug Challenges

EasyManual swap loses original valueEasysort() mutates the original arrayHardIterator is single-use — second loop produces nothingMediumCustom error class not extending Error

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab