Resolving TypeError: Cannot convert undefined or null to object in JavaScript

Nov 07, 2025 · Programming · 18 views · 7.8

Keywords: JavaScript | TypeError | Object Conversion Error | null Handling | undefined Handling | Object.keys | Defensive Programming

Abstract: This article provides an in-depth analysis of the common TypeError in JavaScript, focusing on why Object.keys() throws exceptions when handling undefined or null values. Through practical code examples, it explains specific error scenarios and offers comprehensive solutions. Combining Q&A data and reference articles, it systematically organizes best practices for type checking, conditional judgments, and error handling to help developers fundamentally avoid such issues.

Error Cause Analysis

In JavaScript development, TypeError: Cannot convert undefined or null to object is a common runtime error. This error typically occurs when calling functions that expect an object as an argument but receive undefined or null values instead.

Typical Error Scenarios

The most common error scenario involves using the Object.keys() method:

// Error examples
Object.keys(null)      // Throws TypeError
Object.keys(undefined) // Throws TypeError

// Correct usage
Object.keys({'key': 'value'}) // Returns ['key']

Case Study Analysis

In the provided code example, the problem occurs in the custom stringify function:

var stringify = function(obj) {
  // ...other condition checks...
  if (obj === 'null') { return null;} // Problem here
  // ...other condition checks...
  if (Array.isArray(obj)) { 
    return obj.map(function (e) {
        return stringify(e);
    });
  } else {
    var keys = Object.keys(obj);   // When obj is null, this throws error
    var container = keys.map(function (k) {
        return k + ': ' + stringify(obj[k]);
    });
    return '{' + container.join(', ') + '}';
  }
};

The key issue lies in the conditional check if (obj === 'null'). This condition checks for the string "null" rather than the actual null value. When null is passed, this condition doesn't trigger, and the program continues to execute Object.keys(obj), where Object.keys(null) throws the TypeError.

Solution

The fix involves correcting the type checking condition:

// Fixed code
if (obj === null) { return null; } // Remove quotes, directly compare null value

A complete fixed version should include proper handling of both null and undefined:

var stringify = function(obj) {
  if (typeof obj === 'function') { return undefined; }
  if (typeof obj === 'undefined') { return undefined; }
  if (typeof obj === 'number') { return obj; }
  if (obj === null) { return null; } // Fix: direct null comparison
  if (typeof obj === 'boolean') { return obj; }
  if (typeof obj === 'string') { return '"' + obj + '"'; }
  if (Array.isArray(obj)) { 
    return obj.map(function (e) {
        return stringify(e);
    });
  } else {
    var keys = Object.keys(obj);
    var container = keys.map(function (k) {
        return k + ': ' + stringify(obj[k]);
    });
    return '{' + container.join(', ') + '}';
  }
};

Defensive Programming Practices

To avoid similar errors, adopt defensive programming strategies:

1. Strict Type Checking

function safeObjectKeys(obj) {
  if (obj === null || obj === undefined) {
    return [];
  }
  return Object.keys(obj);
}

2. Using Optional Chaining

// Modern JavaScript
const keys = obj?.constructor === Object ? Object.keys(obj) : [];

3. Parameter Validation

function processObject(obj) {
  if (typeof obj !== 'object' || obj === null) {
    throw new Error('Expected an object, but received: ' + typeof obj);
  }
  // Object processing logic
}

Related Error Patterns

Based on reference article cases, similar errors may occur in other scenarios:

Object.entries() Errors

// Error examples
Object.entries(null)     // Throws TypeError
Object.entries(undefined) // Throws TypeError

Object.assign() Errors

// Error example
Object.assign(undefined, {}) // Throws TypeError

// Correct usage
if (targetObject) {
  Object.assign(targetObject, sourceObject);
}

Function.getPrototypeOf() Errors

// May occur in third-party libraries
Object.getPrototypeOf(undefined) // Throws TypeError

Testing and Debugging Recommendations

To ensure code robustness, consider:

1. Writing Comprehensive Unit Tests

describe('stringify function', function() {
  it('should handle null values correctly', function() {
    expect(stringify(null)).toBe(null);
  });
  
  it('should handle undefined values correctly', function() {
    expect(stringify(undefined)).toBe(undefined);
  });
  
  it('should handle objects correctly', function() {
    expect(stringify({key: 'value'})).toBe('{key: "value"}');
  });
});

2. Using Debugging Tools

Utilize browser developer tools or Node.js debugging features to set breakpoints at potential error locations and observe actual variable values.

3. Code Review

During code reviews, pay special attention to null and undefined handling, ensuring all code using object methods has appropriate protection measures.

Conclusion

The root cause of TypeError: Cannot convert undefined or null to object lies in JavaScript's type system characteristics. While null and undefined are primitive values, they cause errors when treated as objects in certain contexts. Through strict type checking, defensive programming, and comprehensive testing, developers can effectively prevent such errors.

In practical development, always validate values that might be null or undefined, especially when using methods like Object.keys(), Object.entries(), and Object.assign() that expect object parameters. This good programming practice not only prevents runtime errors but also enhances code maintainability and reliability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.