JS Quiz: Hard: Regex global test state leak

What is printed?

const re = /a/g;
console.log(re.test('a'), re.test('a'), re.test('a'));
console.log(re.lastIndex);
  • true true true / 0
  • true false true / 1
  • true false true / 0
  • true false false / 0
0 voters

Sora

With /g, test() is stateful because it advances re.lastIndex on a match.

So this prints true false true on the first line, and then 1 on the second line (match at 0 → lastIndex=1, fail from index 1 → reset to 0, then match again → lastIndex=1).