javascriptobjectpropertiesobject-propertiesobject-property

While using the Object.defineProperties in JavaScript I am getting as ' undefined' on newly defined property .How to fix it..?


const object1 = {
    firstName : 'Shashidhar',
    lastName : 'B M ',
    rollNo : 5678,
    rank : 23456

}

Object.defineProperties(object1,{
    property1 : {
    results : 'selected'
    }
});


console.log(object1.property1)
console.log(object1.firstName);

expected output

selected
shashidhar

actual output

undefined
shashidhar

Solution

  • You want value rather than results to specify the property's value:

    const object1 = {
        firstName : 'Shashidhar',
        lastName : 'B M ',
        rollNo : 5678,
        rank : 23456
    }
    
    Object.defineProperties(object1,{
        property1 : {
        value : 'selected'
        }
    });
    
    
    console.log(object1.property1)
    console.log(object1.firstName);

    See the documentation on MDN.