{"id":174,"date":"2016-04-26T08:10:21","date_gmt":"2016-04-26T08:10:21","guid":{"rendered":"http:\/\/muthu.co\/?p=174"},"modified":"2021-01-02T14:06:03","modified_gmt":"2021-01-02T14:06:03","slug":"different-ways-of-setting-a-value-to-a-javascript-object","status":"publish","type":"post","link":"http:\/\/write.muthu.co\/different-ways-of-setting-a-value-to-a-javascript-object\/","title":{"rendered":"Different ways of setting a value to a Javascript object"},"content":{"rendered":"
\/\/create an object\r\nvar myVar = {};\r\n\r\n\/\/1. set value using dot\r\nmyVar.key = \"myvalue\";\r\n\r\n\/\/2. set value using square brackets\r\nmyVar[\"key2\"] = \"myValue2\"\r\n\r\n\/\/3. set value using defineProperty\r\nObject.defineProperty(myVar,\"key3\",{ \r\n value : \"myValue3\" \r\n });<\/pre>\nSetting values using the dot syntax or\u00a0square brackets is pretty easy to understand but using defineProperty seems\u00a0unusual. As you can see in the code, the defineProperty function of Object takes three parameters.<\/p>\n
Object.defineProperty(obj, prop, descriptor)<\/code><\/p>\n
obj - The object variable\r\nprop - the name of the property that needs to be updated in our variable\r\ndescriptor - this parameter helps us in making our object immutable or mutable.<\/pre>\nThe descriptor\u00a0is an object that can take four parameters<\/p>\n
Object.defineProperty(obj, 'key', {\r\n enumerable: false, \/\/default is false\r\n configurable: false, \/\/default is false\r\n writable: false, \/\/default is false\r\n value: 'static'\r\n});<\/pre>\nAbout\u00a0writable<\/em><\/span><\/h4>\n
When you set a value to a property using defineProperty, you are making it\u00a0an immutable property, i.e you cannot change its value. Take a look at the snap below.<\/p>\n