Quick Answer

Object is undefined/null when trying to set properties. Initialize objects before use, check object existence, or use optional assignment patterns.

Understanding the Issue

This error happens when trying to assign values to properties of undefined or null objects. Common scenarios include uninitialized objects, failed object creation, incorrect destructuring, or accessing nested properties on missing parent objects.

The Problem

This code demonstrates the issue:

Javascript Error
// Problem 1: Setting property on undefined object
let user;
user.name = "John"; // TypeError: Cannot set property name of undefined

// Problem 2: Nested object assignment
const config = {};
config.database.host = "localhost"; // TypeError: Cannot set property host

// Problem 3: Array element assignment
let items;
items[0] = "first item"; // TypeError: Cannot set property 0 of undefined

The Solution

Here's the corrected code:

Javascript Fixed
// Solution 1: Initialize objects before use
let user = {}; // Initialize empty object
user.name = "John"; // Now works
user.age = 30;

console.log("User:", user);

// Solution 2: Check object existence before assignment
function safeAssign(obj, property, value) {
    if (obj && typeof obj === "object") {
        obj[property] = value;
        return true;
    } else {
        console.warn("Cannot assign property to undefined object");
        return false;
    }
}

let testUser;
safeAssign(testUser, "name", "Alice"); // Safe, shows warning

testUser = {};
safeAssign(testUser, "name", "Alice"); // Works
console.log("Test user:", testUser);

// Solution 3: Proper nested object initialization
const config = {
    database: {} // Initialize nested object
};

config.database.host = "localhost";
config.database.port = 5432;
console.log("Config:", config);

// Solution 4: Safe array initialization
let items = []; // Initialize empty array
items[0] = "first item";
items.push("second item");
console.log("Items:", items);

// Solution 5: Handle function return values
function getUser(id) {
    if (id > 0) {
        return { id: id, name: `User ${id}` };
    }
    return null;
}

function updateUserStatus(userId, status) {
    const user = getUser(userId);
    
    if (user) {
        user.status = status;
        console.log("Updated user:", user);
    } else {
        console.log("User not found, cannot update status");
    }
}

updateUserStatus(1, "active"); // Works
updateUserStatus(-1, "active"); // Safe handling

Key Takeaways

Initialize objects before setting properties. Check if objects exist before assignment. Use safe assignment patterns for nested objects. Handle function return values that might be undefined.