How to Add Property to an object in JavaScript?

An object in JavaScript is a collection of properties, and these properties are essentially key-value pairs.
Properties define the characteristics of an object in JavaScript, and these properties can be modified, removed, and even added dynamically even after the object is created.


Few ways to add properties to JavaScript objects are

  • Using dot notation.
  • Using bracket notation [].
  • Using the DefinProperty() method.
  • Using the Object.asign() method
  • Using the spread operator.

Using dot notation:

Object in JavaScript is a collection of unordered properties, and these properties are basically key-value pairs that define the characteristics of an object. Let us take an example of an object in JavaScript where we will define some of the properties inside it.

Note: Just like JavaScript variables, object names & their properties are also case-sensitive

//here car is object and brand and year are it properties
const car = {
  brand: 'FORD',   //added property. 
  year: 2024       //added property.
};

//let see how to read value from above property within car object

console.log(car.brand);  // output will be FORD
console.log(car.year);   // output will be 2024

Let’s add new property in car object:

//syntax is :
object.new_property = new_value;

car.power=1500cc;

//let's see how to read NEW property from car object

console.log(car.power);  // output will be 1500cc

Note: If we try to use any special character or numeric digit in the property name while adding using dot notation, it will generate a syntax error. Please check below property name, I have used “12power” instead of “power” and it will cause error.

car.12power=1500cc;

//It will throw error as 
//SyntaxError: Invalid or unexpected token

Using Square Brackets Notation [ ]

As we have discussed above, there are some disadvantages while working with dot notation in cases where the property name is invalid variable identifier (say all digits, having spaces, special characters).

To handle such cases, we can imagine object as an associative array and can use square bracket notation to add new properties inside an object.

Syntax

object['new_property'] = new_value;

car['power']='1500cc';

Using Object.defineProperty() Method:

JavaScript object class provides the defineProperty() method and using this, we can modify an existing object or add property to object JavaScript. This method returns the modified object and also allows us to control or configure the behavior of the properties

Syntax

Object.defineProperty(obj, new_property, configuration); 

//Object.defineProperty() method of JavaScript to define new properties to an existing object 
//JavaScript example code to demonstrate the use of Object.defineProperty() method
let obj = {}; //empty JavaScript object obj
Object.defineProperty(obj, 'id', { //using Object.defineProperty() method of JavaScript object class 
  value: 101,
  writable: false //configured writable property as false, and hence, the id property of object obj can't be changed now
});


obj.id = 412; //no effect on 'id' property
console.log("Object ID:",obj.id); //prints 101


Object.defineProperty(obj, 'name', { //using Object.defineProperty() method of JavaScript object class 
  value: 'CodeConfig',
  writable: true //configured writable property as true, and hence, the name property of object obj can be changed now
});


obj.name = 'Mayank Jain'; //modifying the name property of object obj (writable property is set to true)
console.log("Object Name:",obj.name); //prints 'code Config'

Using Object.assign() Method

There is another interesting way by which we can add property to object JavaScript i.e, by using the Object.assign() method. This method allows us to add properties of one source object to another target object. We can just define all those properties inside the source object that we need to add to an existing target object.

Syntax

//Object.assign() method 

Object.assign(target, source); 
let student = { name: 'Raj', age: 21 };
let info = { gender: 'Male', nationality: 'Indian' };

Object.assign(student,info); //assigning or adding properties of info object to student object
console.log(student); //having properties of info object as well

Output:

{ name: 'Raj', age: 21, gender: 'Male', nationality: 'Indian' }
{ gender: 'Male', nationality: 'Indian' }

Using Spread Operator (…)

There is another unique way to add property to object JavaScript by using the spread operator. Spread operator (…) creates a copy of the existing object with all its properties and therefore, using inline property definition, we can further add more properties to that object. Let us look at the syntax.

Syntax

//adding property1 & property2 to object using spread operator of JavaScript
object = { ...object, property1: value1, property2: value2 }

//adding all properties from new_object to object using spread operator of JavaScript
object = { ...object, ...new_object }
//JavaScript example code to demonstrate the use of Spread operator syntax method

let obj = {name: 'RAM', id: '101'}; 
//JavaScript object named obj with some defined properties inside it 


console.log(obj); 
//prints object obj before adding new properties 


obj = {...obj,nationality: 'Indian',gender: 'Male'};
 //adding more properties to an existing object named obj using spread operator (...) 


console.log(obj);
 //prints object obj after adding new properties using spread operator 


let obj2 = {country: 'India', city: 'Chandigarh', pincode: '110011'}; 
//JavaScript object named obj2 with some defined properties inside it 


let obj3 = {name: 'Ramesh', lastName: 'Kumar', age: '31', gender: 'Male'};
 //Another JavaScript object named obj3 with some defined properties inside it


obj3 = {...obj3, ...obj2}; 
//adding properties of object obj2 to the end of object obj3 using JavaScript spread operator


console.log(obj3);
 //prints object obj3 after adding new properties of obj2 inside it using spread operator 

Output

{ name: 'RAM', id: '101' }
{ name: 'RAM',
  id: '101',
  nationality: 'Indian',
  gender: 'Male' }
{ name: 'Ramesh',
  lastName: 'Kumar',
  age: '31',
  gender: 'Male',
  country: 'India',
  city: 'Chandigarh',
  pincode: '110011' }

Leave a Reply

Your email address will not be published. Required fields are marked *