Interview frequency: …
Short answer
It is a quantitative measure of the number of independent logical paths in a function, calculated as the number of branching points (if, while, for, case, &&, ||) plus one.
Explanation
As cyclomatic complexity rises above 10, more unit tests are needed to cover every scenario, and the chance of unexpected bugs increases. Reduce complexity by: (1) using guard clauses for early returns to remove deep nesting (the Arrow Anti-pattern); (2) replacing conditionals with polymorphism; and (3) extracting complex methods.
Code example
// Before (high complexity and deep nesting):
function process(user) {
if (user != null) {
if (user.isActive) {
if (user.hasPermission) { doSomething(); }
}
}
}
// After (Guard Clauses - low, flat complexity):
function process(user) {
if (!user || !user.isActive || !user.hasPermission) return;
doSomething();
}Common mistakes
- Writing five or six levels of nested if blocks, making code very difficult to read and state paths impossible to trace.