Skip to content

Latest commit

 

History

History
61 lines (41 loc) · 1.8 KB

no-typeof-undefined.md

File metadata and controls

61 lines (41 loc) · 1.8 KB

Disallow comparing undefined using typeof

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Checking if a value is undefined by using typeof value === 'undefined' is needlessly verbose. It's generally better to compare against undefined directly. The only time typeof is needed is when a global variable potentially does not exists, in which case, using globalThis.value === undefined may be better.

Historical note: Comparing against undefined without typeof was frowned upon until ES5. This is no longer a problem since all engines currently in use no longer allow reassigning the undefined global.

Fail

function foo(bar) {
	if (typeof bar === 'undefined') {}
}
import foo from './foo.js';

if (typeof foo.bar !== 'undefined') {}

Pass

function foo(bar) {
	if (foo === undefined) {}
}
import foo from './foo.js';

if (foo.bar !== undefined) {}

Options

checkGlobalVariables

Type: boolean
Default: false

The rule ignores variables not defined in the file by default.

Set it to true to check all variables.

// eslint unicorn/no-typeof-undefined: ["error", {"checkGlobalVariables": true}]
if (typeof undefinedVariable === 'undefined') {} // Fails
// eslint unicorn/no-typeof-undefined: ["error", {"checkGlobalVariables": true}]
if (typeof Array === 'undefined') {}  // Fails