In JavaScript, determining whether a variable is undefined is a fundamental task, yet it often becomes a source of confusion due to nuances in the language. With JavaScript being a loosely-typed language, understanding the nuances of checking variable definitions is critical for developers working on modern web applications, frameworks, and libraries.
What does "undefined" mean in JavaScript?
A variable is undefined in JavaScript when:
- It has been declared but not assigned a value
- It is explicitly set to undefined
- It's an object property that doesn't exist
- A function parameter wasn't passed
- A function doesn't return a value
javascript
// Declared but not assigned
let x;
console.log(x); // undefined
// Explicit assignment
let y = undefined;
console.log(y); // undefined
// Non-existent property
const obj = { a: 1 };
console.log(obj.b); // undefined
// Missing function parameter
function greet(name) {
console.log(name); // undefined if not passed
}
greet();
// No return value
function noReturn() {}
console.log(noReturn()); // undefinedThis article delves into how to accurately check for undefined variables and explores why this knowledge is vital in modern web and application development.
Join Index.dev to connect with global companies, access top JavaScript projects, and build a rewarding remote career.
Quick Reference: JavaScript Check if Undefined
Need to quickly check if a variable is undefined in JavaScript? Here are the fastest methods:
javascript
// Method 1: typeof (safest - works for undeclared variables)
if (typeof myVar === 'undefined') {
console.log('myVar is undefined');
}
// Method 2: Strict equality (for declared variables)
let myVar;
if (myVar === undefined) {
console.log('myVar is undefined');
}
// Method 3: TypeScript check if undefined
// TypeScript
function greet(name?: string) {
if (name === undefined) {
return 'Hello, Guest!';
}
return `Hello, ${name}!`;
}Which method should you use?
Scenario | Best Method | Why |
|---|---|---|
Unknown/undeclared variable | typeof x === 'undefined' | Won't throw ReferenceError |
Declared variable | x === undefined | Faster, more precise |
Object property | obj.prop === undefined | Direct comparison |
TypeScript | x === undefined | Type-safe with strict mode |
Optional chaining | obj?.prop | Returns undefined if chain breaks |
Related: How to Check Variable Types in JavaScript
Method 1: JavaScript Undefined Check Using typeof
The typeof operator is the safest way to check if a variable is undefined in JavaScript, especially for potentially undeclared variables.
Syntax:
javascript
typeof variable === 'undefined'Code Example — JS check if undefined:
javascript
// Check undeclared variable (safe - no error)
if (typeof undeclaredVar === 'undefined') {
console.log('Variable is undefined or undeclared');
}
// Check declared but unassigned variable
let declaredVar;
if (typeof declaredVar === 'undefined') {
console.log('declaredVar is undefined'); // This runs
}
// Check assigned variable
let assignedVar = 'hello';
if (typeof assignedVar === 'undefined') {
console.log('This will NOT run');
}
// Check function parameter
function processData(data) {
if (typeof data === 'undefined') {
console.log('No data provided');
return;
}
// Process data...
}
// Check object property
const config = { debug: true };
if (typeof config.verbose === 'undefined') {
console.log('verbose setting not defined'); // This runs
}
Why typeof is safe:
javascript
// This throws ReferenceError:
if (neverDeclared === undefined) { } // ❌ Error!
// This is safe:
if (typeof neverDeclared === 'undefined') { } // ✅ No error
When to use typeof:
- Checking global variables that may not exist
- Checking variables in unknown scope
- Feature detection in browsers
- Safe checks in library code
JavaScript Check if Variable is Defined
Sometimes you need the opposite check — verifying that a variable IS defined (not undefined). Here's how to check if a variable is defined in JavaScript:
Method 1: typeof for "is defined" check
javascript
// JS check if variable is defined
if (typeof myVar !== 'undefined') {
console.log('myVar is defined');
}
// Safe check for potentially undeclared variables
if (typeof possiblyUndeclared !== 'undefined') {
console.log('Variable exists and is defined');
}Method 2: Strict inequality for declared variables
javascript
let myVar = 'hello';
// Check if defined (declared variables only)
if (myVar !== undefined) {
console.log('myVar is defined:', myVar);
}Method 3: Truthy check (with caveats)
javascript
let myVar = 'hello';
// Quick check - but beware of falsy values!
if (myVar) {
console.log('myVar is defined and truthy');
}
// ⚠️ Warning: These are defined but falsy:
let zero = 0; // defined, but falsy
let empty = ''; // defined, but falsy
let isFalse = false; // defined, but falsy
if (zero) { } // Won't execute even though zero IS definedMethod 4: Check with nullish coalescing
javascript
// Provide default if undefined or null
const value = myVar ?? 'default';
// Different from || which catches all falsy values
const config = {
timeout: 0, // intentionally 0
};
// Wrong: treats 0 as "not set"
const timeout1 = config.timeout || 5000; // 5000 (wrong!)
// Correct: only replaces undefined/null
const timeout2 = config.timeout ?? 5000; // 0 (correct!)Complete "is defined" check function:
javascript
// Check if a variable is defined (not undefined)
function isDefined(value) {
return typeof value !== 'undefined';
}
// Check if defined and not null
function isDefinedAndNotNull(value) {
return value !== undefined && value !== null;
}
// Usage
let a;
let b = null;
let c = 'hello';
console.log(isDefined(a)); // false
console.log(isDefined(b)); // true (null is defined!)
console.log(isDefined(c)); // true
console.log(isDefinedAndNotNull(a)); // false
console.log(isDefinedAndNotNull(b)); // false
console.log(isDefinedAndNotNull(c)); // true
Method 2: Check Undefined Object Properties
Code Example:
javascript
// Using 'in' operator vs undefined check
const obj = { a: 1, b: undefined };
// Check if property exists (even if undefined)
console.log('a' in obj); // true
console.log('b' in obj); // true
console.log('c' in obj); // false
// Check if property value is undefined
console.log(obj.a === undefined); // false
console.log(obj.b === undefined); // true
console.log(obj.c === undefined); // true
// hasOwnProperty (ignores inherited properties)
console.log(obj.hasOwnProperty('a')); // true
console.log(obj.hasOwnProperty('c')); // false
Method 3: JS Check if Undefined Using void 0
Code Example:
javascript
// void 0 always returns undefined
let myVar;
if (myVar === void 0) {
console.log('myVar is undefined');
}
// Why use void 0?
// In old JavaScript, undefined could be reassigned
// void 0 is guaranteed to return undefined
Also Read: 6 Easy Ways To Convert String to Date in JavaScript
Method 4: Type Checking in Modern JavaScript with TypeScript
TypeScript, a superset of JavaScript, provides static type checking at compile time, which eliminates many runtime errors and ensures robust code.
Code Example:
// Advanced type checking patterns
type TypePredicate<T> = (value: unknown) => value is T;
type Nullable<T> = T | null | undefined;
// Custom type guard implementation
const createTypeGuard = <T>(check: (value: unknown) => boolean): TypePredicate<T> =>
(value: unknown): value is T => check(value);
// Implementation examples
const isNonEmptyString = createTypeGuard<string>(
(value): value is string =>
typeof value === 'string' && value.trim().length > 0
);
const isValidDate = createTypeGuard<Date>(
(value): value is Date =>
value instanceof Date && !isNaN(value.getTime())
);Explanation:
TypeScript's type system provides zero-runtime-cost type checking through erasable type annotations. Custom type guards enable runtime type checking while maintaining type inference. The implementation pattern allows for composition of type checks while preserving type safety.
Adopt TypeScript for larger codebases or when working in teams to maintain strict type safety. This is particularly valuable in enterprise environments. Learn more about TypeScript and its benefits.
TypeScript Check if Undefined
How do you check if a variable is undefined in TypeScript? TypeScript adds type safety, but you still need to handle undefined values properly.
Method 1: Strict equality check
typescript
// TypeScript check if undefined
function greet(name: string | undefined) {
if (name === undefined) {
return 'Hello, Guest!';
}
return `Hello, ${name}!`;
}Method 2: Optional parameters
typescript
// Optional parameter (automatically string | undefined)
function greet(name?: string) {
if (name === undefined) {
return 'Hello, Guest!';
}
return `Hello, ${name}!`;
}
// With default value
function greetWithDefault(name: string = 'Guest') {
return `Hello, ${name}!`;
}Method 3: Type guards
typescript
// Custom type guard for undefined check
function isDefined<T>(value: T | undefined): value is T {
return value !== undefined;
}
// Usage
function processItems(items?: string[]) {
if (isDefined(items)) {
// TypeScript knows items is string[] here
items.forEach(item => console.log(item));
}
}Method 4: Optional chaining in TypeScript
typescript
interface User {
name: string;
address?: {
city?: string;
};
}
function getCity(user: User): string {
// Optional chaining returns undefined if any part is missing
return user.address?.city ?? 'Unknown';
}
const user1: User = { name: 'John' };
const user2: User = { name: 'Jane', address: { city: 'NYC' } };
console.log(getCity(user1)); // 'Unknown'
console.log(getCity(user2)); // 'NYC'Method 5: Non-null assertion (use carefully)
typescript
// When you're SURE a value isn't undefined
function processUser(user: User | undefined) {
// ⚠️ Only use when you're certain
const name = user!.name; // Asserts user is not undefined
}Method 6: strictNullChecks compiler option
json
// tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}With strictNullChecks enabled, TypeScript will error if you try to use a potentially undefined value without checking it first:
typescript
function getLength(str: string | undefined): number {
// Error: Object is possibly 'undefined'
// return str.length;
// Correct: Check first
if (str === undefined) {
return 0;
}
return str.length; // TypeScript knows str is string here
}TypeScript undefined check best practices:
Scenario | Best Approach | Example |
|---|---|---|
Optional parameter | Default value or ? | function fn(x?: string) |
Nullable type | Union with undefined | let x: string | undefined |
Object property | Optional chaining | obj?.prop?.value |
Default value | Nullish coalescing | value ?? 'default' |
Type narrowing | Explicit check | if (x !== undefined) |
See also: JavaScript vs TypeScript Comparison or Hire TypeScript Developers with Index.dev here.
Method 5: JavaScript Check Undefined with Strict Equality (===)
The strict equality operator (===) in JavaScript checks whether two values are equal without performing type conversion. This means both the value and the type must be identical for the comparison to return true.
Code Example:
javascript
// Direct comparison with undefined
let myVar;
if (myVar === undefined) {
console.log('myVar is undefined');
}
// Works for object properties too
const obj = { a: 1 };
if (obj.b === undefined) {
console.log('obj.b is undefined');
}
Explanation:
The strict equality implementation handles edge cases including cross-realm undefined values and objects with undefined [[Class]] tags. The property checker uses hasOwnProperty with Function.prototype.call to handle objects with null prototypes or overridden hasOwnProperty methods.
Best Practice:
⚠️ Important: Only use strict equality for declared variables. For undeclared variables, use typeof.
console.log(typeof x !== 'undefined' && x === undefined);Here, typeof x returns the string 'undefined' if x is undeclared or its value is undefined, preventing any errors. This combined check ensures that x is both declared and strictly equals undefined.
For more information on strict equality, refer to the MDN Web Docs on Equality comparisons and sameness or you can check out this video.
Method 6: JavaScript Undefined Check with Optional Chaining
Code Example:
javascript
// Optional chaining (?.) returns undefined if chain breaks
const user = {
name: 'John',
// address is missing
};
// Without optional chaining (throws error):
// console.log(user.address.city); // TypeError!
// With optional chaining (safe):
console.log(user.address?.city); // undefined
// Combine with nullish coalescing for defaults:
console.log(user.address?.city ?? 'No city'); // 'No city'
…
Each method implementation focuses on performance optimization, type safety, and enterprise-scale reliability while maintaining clean, maintainable code patterns. By understanding and appropriately applying these methods, developers can effectively determine whether a variable is undefined in JavaScript, ensuring robust and error-free code.
Read More: 7 Ways to Insert Nodelist in JavaScript
Summary: JavaScript Check if Undefined
Here's a quick decision guide for checking undefined in JavaScript and TypeScript:
Scenario | Best Method | Code |
|---|---|---|
Undeclared variable | typeof | typeof x === 'undefined' |
Declared variable | Strict equality | x === undefined |
Object property | Optional chaining | obj?.prop === undefined |
Function parameter | Default value | function fn(x = 'default') |
TypeScript | Strict equality + types | if (x === undefined) |
With default value | Nullish coalescing | x ?? 'default' |
Key takeaways:
- Use typeof for safe checks on potentially undeclared variables
- Use === undefined for declared variables (faster, more precise)
- Use optional chaining (?.) for nested object properties
- Use nullish coalescing (??) for default values
- In TypeScript, enable strictNullChecks for compile-time safety
Common mistakes to avoid:
- ❌ Using == instead of === (catches null too)
- ❌ Checking undeclared variables without typeof
- ❌ Using || when you mean ?? (treats 0 and '' as falsy)
- ❌ Forgetting that TypeScript optional parameters are | undefined
Need help with JavaScript or TypeScript development? Hire expert JavaScript developers from Index.dev.
For Developers: Unlock high-paying remote opportunities with Index.dev! Join our network to work with global companies and take your JavaScript career to the next level.
For Clients: Hire elite JavaScript developers through Index.dev. Access the top 5%, get matches in 48 hours, and enjoy a 30-day risk-free trial!