Optional Capture Groups
What you'll learn: How capture groups behave when they're optional and don't participate in the match.
When you combine capture groups with the ? quantifier, you're making that entire group optional. If the pattern matches without needing the optional part, that capture group will exist in the results array but contain undefined instead of a matched string.
The Core Idea
Think of optional capture groups like booking a table for friends who might show up. You've reserved the seat (the group exists in your results), but if they don't come, that seat remains empty (undefined). The match can still succeed—you just need to check whether that particular group captured anything.
Here's a simple example:
const pattern = /hello( world)?/;
const result1 = pattern.exec("hello world");
console.log(result1[1]); // " world"
const result2 = pattern.exec("hello");
console.log(result2[1]); // undefined
Both strings match the pattern, but in the second case, the optional group didn't participate. The capture group slot result2[1] exists but holds undefined.
Why This Matters
When processing captured values, you must account for possible undefined values:
const pattern = /(\d{3})-?(\d{4})/; // Optional dash
const result = pattern.exec("5551234");
console.log(result[1]); // "555"
console.log(result[2]); // "1234"
// The dash group wasn't captured, but groups are numbered by parentheses position
Always check if an optional capture is undefined before using it, or provide defaults when destructuring or processing the results.
Key Takeaway: Optional capture groups with ? will be undefined in the results array when the optional part doesn't match, but the overall pattern can still succeed.