JavaScript Object defineProperties() Method (original) (raw)

Last Updated : 12 Jul, 2024

The **Object.defineProperties() method in JavaScript is a standard built-in Object that defines a new or modifies existing properties directly on an object and it returns the object.

**Syntax:

Object.defineProperties(obj, props)

**Parameters:

**Return Value:

**Example 1: In this example, we will define new properties to an object using the Object.defineProperties() method in JavaScript.

javascript `

const geek = {};

Object.defineProperties(geek, { prop1: { value: "geeksforgeeks", writable: true }, prop2: {} });

console.log(geek.prop1); console.log(geek.prop2);

`

**Output:

"geeksforgeeks"
undefined

**Example 2: In this example, we will define new properties and modify some properties of an object using the Object.defineProperties() method in JavaScript.

javascript `

let geek = {}; Object.defineProperties(geek, { 'prop1': { value: "Geeks", writable: true }, 'prop2': { value: 'Hello', writable: false } }); console.log(geek.prop2); console.log(geek.prop1);

const geek1 = {}; Object.defineProperties(geek1, { prop1: { value: "Hi", value: "Hello", value: "Namaste", }, prop2: { value: " And ", }, prop3: { value: "learn", value: "Stay Safe", } });

console.log(geek1.prop1, geek1.prop2, geek1.prop3);

`

**Output:

"Hello"
"Geeks"
"Namaste" " And " "Stay Safe"

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

**Supported Browsers:

The browsers supported by Object.defineProperties() method are listed below:

What does the Object.defineProperties() method do in JavaScript?

The Object.defineProperties() method defines new or modifies existing properties directly on an object, returning the object.

Can Object.defineProperties() be used to freeze properties?

You can create non-writable and non-configurable properties using Object.defineProperties(), effectively making them immutable.

How does Object.defineProperties() handle deeply nested properties?

Object.defineProperties() only defines or modifies properties at the top level of the object. It does not traverse nested objects.

How does Object.defineProperties() interact with strict mode?

In strict mode, attempting to define or modify properties in a way that violates property attributes will throw an error.

What is the most common use of the Object.defineProperties() method?