This rule raises an issue when code uses typeof variable === 'undefined' or typeof variable !== 'undefined' to check if a
value is undefined.
Using typeof to check for undefined values is unnecessarily verbose and makes code harder to read. The pattern
typeof value === 'undefined' was historically necessary in older JavaScript versions (pre-ES5) because the global undefined
could be reassigned. However, this is no longer a concern in modern JavaScript environments.
The typeof operator returns a string, which means you’re comparing strings rather than directly checking the value. This adds an extra
layer of complexity that serves no purpose in most cases. Direct comparison with undefined is more straightforward and expressive.
The only legitimate use case for typeof when checking undefined is when you need to verify if a global variable exists without
throwing a ReferenceError. However, even in this case, using globalThis.variableName === undefined is often a clearer alternative.
This issue primarily affects code readability and maintainability. While it doesn’t introduce security vulnerabilities or runtime errors, it makes
the codebase more verbose and harder to understand. Developers may spend extra time parsing the intent of typeof checks when a simple
comparison would be clearer.
Replace typeof checks with direct comparison to undefined. This makes the code more concise and easier to read.
function processValue(value) {
if (typeof value === 'undefined') { // Noncompliant
return 'No value provided';
}
return value;
}
function processValue(value) {
if (value === undefined) {
return 'No value provided';
}
return value;
}