What is Object.defineProperty() in Javascript?

The Object.defineProperty() method defines a new property to an object or modifies an existing property of an object.

The defineProperty() method is declared as follows:

Object.defineProperty( obj, prop, desc)
  • obj: The object whose property is defined.
  • prop: The name or symbol of the property that is set.
  • desc: The descriptor of the property that is set.

Property descriptor

We can use the property descriptor to do the following:

  • Change the value of the property, as shown below:
Object.defineProperty( obj, prop, {value: "new val"})
  • Change the meta-data of the property, as shown below:
Object.defineProperty( obj, prop, {writable: bool})

Object.defineProperty( obj, prop, {enumerable: bool})

Object.defineProperty( obj, prop, {configureable: bool})

Where bool is either true or false.

Return value

The defineProperty() method returns the object obj with the property prop set.

Browser compatibility

The following browsers support the defineProperty() method:

  • Edge 12
  • Firefox 4
  • Google Chrome 5
  • Internet Explorer 9
  • Opera 11.6
  • Safari 5.1

Codes

Code 1

Consider the code snippet below, which demonstrates the use of the defineProperty() method where the object’s property is modified.

var Student = { name: 'Ali', rollNo: '123'}
console.log(Student)
//modifying property
Object.defineProperty(Student, "rollNo", {value: "234"})
console.log(Student)

Code 2

Consider the code snippet below, which demonstrates the use of the defineProperty() method where an object’s property is added.

var Student = { name: 'Ali', rollNo: '123'}
console.log(Object.getOwnPropertyNames(Student));//return names of object's properties
//adding property
Object.defineProperty(Student, 'batch', {value: "2021", writeable: true})
console.log(Object.getOwnPropertyNames(Student));//return names of object's properties

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved