skip to Main Content

I have this object

const product = { 
    name: "Laptop", 
    price: 1000, 
    quantity: 5 
  };
console.log(product) //{ name: 'Laptop', price: 1000, quantity: 5 }

but then I should to do this:

const descriptors = { enumerable: false, writable: false };

Object.defineProperties(product, {
    price: { ...descriptors },
    quantity: { ...descriptors },
});

and in console I get this after using defineProperties:

console.log(product) //{ name: 'Laptop' }

My question: Why it’s happening?

I expected that the product object will the same but with disables in enumerable and writable only in price and quantity and didn’t understand how it works(defineProperties)
Also tried to write it’s like "price:{ enumerable: false, writable: false }" the same result

2

Answers


  1. You’re setting enumerable to false. Therefore anything that tries to enumerate keys or entries won’t see it.

    Login or Signup to reply.
  2. When you use Object.defineProperties(), you are defining the property descriptors for the object properties you want to modify.

    After applying Object.defineProperties() to product with the descriptors for price and quantity, both properties become non-enumerable and read-only. As a result, when you log the product object, only the name property is shown because it is the only enumerable property. The price and quantity properties are still present in the object, but they won’t show up in the console or be accessible in loops, and you won’t be able to change their values directly.

    if you try to access the price and quantity properties directly, you’ll find that they are still there but are not writable:

    console.log(product.price); // 1000
    console.log(product.quantity); // 5
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search