Saturday, January 31, 2026
HomeLanguagesJavascriptHow to conditionally add a member to an object using JavaScript ?

How to conditionally add a member to an object using JavaScript ?

Objects are the most important data-type and are building blocks for modern JavaScript. They are different from primitive data-types such as String, Number, Boolean, null, etc. But we can make these datatypes as objects by using the new keyword. There are two approaches to conditionally add a member to an object.

Method 1: This method involves checking if the required condition is true and based on that a property is added to the object. 

Example: In this example, if the condition is true then ‘b’ will be added as a member to ‘a’, otherwise not.

Javascript




// Define the object
var a = {};
  
// Check if the condition
// is satisfied
if (someCondition) {
      
    // Add the required 
    // property to the object 
    a.b = 7;
}


Output:

  • When condition is satisfied:

    {b: 7}
  • When condition is not satisfied:

    {}

This approach can also be used in an idiomatic way, using a ternary operator.

Example: In this example, if the condition is true then ‘b’ will be added as a member to ‘a’, otherwise not.

Javascript




var a = {
    // Use the ternary operator to check
    // if the property should be added
    // to the object
    b: (someCondition? 7 : undefined)
};


Output:

  • When condition is satisfied:

    {b: 7}
  • When condition is not satisfied:

    {b: undefined}

Method 2: This method is used to add several members to an object. The jQuery library function $.extend() is used for this method. This however does not copy undefined properties to the object.

Example:

Javascript




var newObject = $.extend({}, {
  a: conditionA ? 7 : undefined,
  b: conditionB ? 9 : undefined,
    
  // More properties as required
});


Output:

  • When the first condition is satisfied:

    {a: 7}
  • When both conditions are satisfied:

    {a: 7, b: 9}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS