Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Cannot set property of null - How to Fix (2026)

What is This Error?

The error TypeError: Cannot set property 'x' of null occurs when you try to assign a value to a property of a variable that is null. This is similar to the "cannot read property" error but happens during assignment.

Common Causes

  • Trying to set property on null variable
  • DOM element not found (querySelector returns null)
  • Object is null before property assignment
  • Accessing nested object properties when parent is null
  • Script runs before DOM is ready

Quick Fix (TL;DR)

Quick Solution
// ❌ Problem
let user = null;
user.name = 'John'; // TypeError!

// ✅ Solution 1: Check if exists
if (user) {
    user.name = 'John';
}

// ✅ Solution 2: Initialize object first
let user = {};
user.name = 'John'; // Works!

// ✅ Solution 3: Optional chaining with nullish coalescing
user = user ?? {};
user.name = 'John';

Common Scenarios & Solutions

Scenario 1: DOM Element Not Found

The most common case - trying to set properties on a DOM element that doesn't exist.

Problem
// Element doesn't exist in HTML
const input = document.querySelector('#username');
input.value = 'John'; // TypeError: Cannot set property 'value' of null

// Typo in selector
const button = document.querySelector('#sumbit-btn'); // typo: sumbit
button.disabled = true; // TypeError!
Solution
// Solution 1: Check if element exists
const input = document.querySelector('#username');
if (input) {
    input.value = 'John';
} else {
    console.error('Input element not found');
}

// Solution 2: Use optional chaining (modern browsers)
const button = document.querySelector('#submit-btn');
if (button) button.disabled = true;

// Solution 3: Wait for DOM to load
document.addEventListener('DOMContentLoaded', () => {
    const input = document.querySelector('#username');
    if (input) input.value = 'John';
});

Scenario 2: Setting Property on Null Object

Trying to set a property on a variable that is explicitly null.

Problem
let user = null;
user.name = 'John'; // TypeError!

// Or from function return
function getUser() {
    return null; // User not found
}

const user = getUser();
user.email = 'john@example.com'; // TypeError!
Solution
// Solution 1: Initialize before use
let user = {}; // Initialize as empty object
user.name = 'John'; // Works!

// Solution 2: Check before setting
let user = null;
if (user === null) {
    user = {};
}
user.name = 'John';

// Solution 3: Use nullish coalescing
let user = null;
user = user ?? {}; // If null, use empty object
user.name = 'John';

// Solution 4: Handle in function
function getUser() {
    return null;
}

const user = getUser() || {}; // Default to empty object
user.email = 'john@example.com'; // Safe now

Scenario 3: Nested Object Property Assignment

Setting a property on a nested object when the parent is null.

Problem
let data = {
    user: null
};

data.user.name = 'John'; // TypeError: Cannot set property 'name' of null

// Or with API response
const response = {
    data: null
};

response.data.items = []; // TypeError!
Solution
// Solution 1: Initialize nested object
let data = {
    user: {} // Initialize as empty object
};
data.user.name = 'John'; // Works!

// Solution 2: Check before setting
let data = {
    user: null
};

if (!data.user) {
    data.user = {};
}
data.user.name = 'John';

// Solution 3: Use nullish coalescing
let data = {
    user: null
};

data.user = data.user ?? {};
data.user.name = 'John';

// Solution 4: Safe assignment function
function safeSet(obj, path, value) {
    const keys = path.split('.');
    let current = obj;
    
    for (let i = 0; i < keys.length - 1; i++) {
        if (!current[keys[i]]) {
            current[keys[i]] = {};
        }
        current = current[keys[i]];
    }
    
    current[keys[keys.length - 1]] = value;
}

let data = { user: null };
safeSet(data, 'user.name', 'John'); // Safe!

Scenario 4: Script Runs Before DOM Ready

JavaScript executes before HTML elements are created.

Problem (HTML)
<!DOCTYPE html>
<html>
<head>
    <script>
        // Runs before body is parsed
        const input = document.querySelector('#username');
        input.value = 'John'; // TypeError: input is null
    </script>
</head>
<body>
    <input id="username" type="text">
</body>
</html>
Solution
<!-- Solution 1: Move script to end of body -->
<body>
    <input id="username" type="text">
    
    <script>
        const input = document.querySelector('#username');
        input.value = 'John'; // Works!
    </script>
</body>

<!-- Solution 2: Use DOMContentLoaded -->
<head>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const input = document.querySelector('#username');
            if (input) input.value = 'John';
        });
    </script>
</head>

<!-- Solution 3: Use defer attribute -->
<head>
    <script defer src="app.js"></script>
</head>

Best Practices

  • Always check if object exists - Use if statements before setting properties
  • Initialize objects - Use {} instead of null for objects you'll modify
  • Use optional chaining - Modern JavaScript feature for safe property access
  • Wait for DOM - Use DOMContentLoaded or defer attribute for scripts
  • Validate selectors - Check if querySelector returns an element
  • Use TypeScript - Catch null assignments at compile time
  • Provide defaults - Use nullish coalescing (??) for default values

Related Errors

Key Takeaways
  • This error occurs when trying to set a property on null
  • Most common with DOM elements that don't exist (querySelector returns null)
  • Always check if object/element exists before setting properties
  • Initialize objects as {} instead of null if you plan to add properties
  • Use DOMContentLoaded or defer to ensure DOM is ready
  • Optional chaining and nullish coalescing help prevent this error

Frequently Asked Questions


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.