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 and Using Brackets.

  • Using Dot Notation: Dot notation is the easiest way to access and change object properties when the property name is a valid JavaScript identifier. Here is the syntax for this:
// Define an object
object.propertyName = null;
  • Using Brackets: Bracket notation offers more flexibility for accessing and changing object properties because it can work with dynamic property names. Here is the syntax for this:
  • // Define an object
    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 Brackets.

    // 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); 

    Output

    { make: 'Toyota', model: null, year: null }

    For Multiple Object Value

    Setting the multiple values of the JavaScript object to null can be done by using a For loop along with object.keys() method. The Object.keys() is used to get an array of the object's property names and iterate over them with a standard for loop.

    Example

    The following is a simple example of setting an object's multiple value to null using object.keys() and for loop.

    const obj = { name: "Joy", age: 25, email: "[email protected]" };
    
    // Get all keys and iterate over them
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
        obj[keys[i]] = null;
    }
    
    console.log(obj);

    Output

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

    Conclusion

    In this article, we have seen how to set the object value to null for two situations: for a specific object value and multiple object values. Setting JavaScript object values to null is helpful for resetting properties while keeping the keys in the object.

    Updated on: 2025-03-17T12:35:38+05:30

    6K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements