.defineProperty()
Published Dec 28, 2023
Contribute to Docs
The .defineProperty()
method defines a property on an object, either creating a new property or modifying an existing one. The method returns the modified object with the specified property.
Syntax
Object.defineProperty(obj, prop, descriptor)
obj
: The object on which to define or modify the property.prop
: The name or Symbol of the property to be defined or modified.descriptor
: An object that contains the property’s configuration, such as value or getter/setter functions.
The syntax above is used to define or modify a property on the object obj
. The method returns the updated object containing the specified property.
Example
In the example below, a name
property is defined using the ``.defineProperty()` method. Then, to check the value of the property, by printing it to the console:
const person = {};Object.defineProperty(person, 'name', {value: 'John',writable: true,enumerable: true,configurable: true,});console.log('Name:', person.name);
This above example will return the following output:
Name: John
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Full-Stack Engineer
A full-stack engineer can get a project done from start to finish, back-end to front-end.Includes 51 CoursesWith Professional CertificationBeginner Friendly150 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours