Set JavaScript object values to null?

Setting object values to null can help reset data, free up memory, or show that a value is no longer needed. In JavaScript, the null value is used to indicate that there is an intentional absence of any object value. This article provides various methods for setting JavaScript object values to null and what that means.

Setting an Object's Values to null

Setting object values to null can be done in two types:

For Specific Object Value

Setting the specific value of JavaScript object to null can be done in two forms:

Using Dot Notation

Dot notation is the easiest way to access and change object properties when the property name is a valid JavaScript identifier.

object.propertyName = null;

Using Bracket Notation

Bracket notation offers more flexibility for accessing and changing object properties because it can work with dynamic property names.

object["propertyName"] = null;

Example

The following is a simple and combined example of setting an object value to null for a specific value using dot notation and bracket notation.

// Define an object
let car = {
    make: "Toyota",
    model: "Camry",
    year: 2020
};

// Set the 'model' property to null using dot notation
car.model = null;

// Set the 'year' property to null using bracket notation
car["year"] = null;

console.log(car);
{ make: 'Toyota', model: null, year: null }

For Multiple Object Values

Setting multiple values of the JavaScript object to null can be done using a for loop along with the Object.keys() method. The Object.keys() method returns an array of the object's property names that you can iterate over.

Using Object.keys() with For Loop

const obj = { name: "Joy", age: 25, email: "joy@example.com" };

// Get all keys and iterate over them
const keys = Object.keys(obj);
for (let i = 0; i 

{ name: null, age: null, email: null }

Using for...in Loop

Alternatively, you can use a for...in loop to iterate directly over object properties:

const person = { firstName: "John", lastName: "Doe", city: "New York" };

// Set all properties to null using for...in loop
for (let key in person) {
    person[key] = null;
}

console.log(person);
{ firstName: null, lastName: null, city: null }

Key Points

  • null vs undefined: Setting a property to null explicitly indicates "no value", while undefined means the property was never set
  • Memory: Setting objects to null can help with garbage collection by removing references
  • Preservation: Setting values to null keeps the object structure intact while clearing the data

Conclusion

Setting JavaScript object values to null is useful for resetting properties while preserving the object structure. Use dot notation for known properties and Object.keys() with loops for setting multiple values to null efficiently.

Updated on: 2026-03-15T23:18:59+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements