Property Descriptor in JavaScript

JavaScript gives us control to define, modify, and configure properties. This is made possible using a property descriptor object, which has the following attributes:

- value 

- writable 

- configurable 

- enumerable 

When we define a property on an object as follows:

var car = {

_doors: 4

};

The property descriptor's value attribute is set to 4, writable (which controls if we can write values to an object property) is set to true, configurable (which controls if we can delete a property) is set to true, and enumerable (which controls if property can be enumerated) is also set to true. We can check these attributes as follows:

var desc = Object.getOwnPropertyDescriptor (car, '_doors');

alert(desc.writable); // true

alert(desc.configurable); // true

alert(desc.value); // 4

alert(desc.enumerable); // true

Another important thing to keep in mind that Object.getOwnPropertyDescriptor works only on 'own' properties and not on 'prototype' properties. Furthermore, we can set all these property descriptor attributes using the Object.defineProperty() as follows:

Object.defineProperty (car, 'name', {

value: 'Audi',

writable: true

});

var desc = Object.getOwnPropertyDescriptor (car, 'name');

alert(car.name);

alert(desc.writable);

alert(desc.enumerable); // If you don't specify it, it defaults to false

alert(desc.configurable); // Didn't specify, so defaults to false

If we don't specify the value of attributes in Object.defineProperty(), they default to false, and that's one important thing to keep in mind. Complete code is given below:

Getter and Setter in JavaScript

We can define properties on an object as follows:

var car = {

_name: 'Audi'

};

We can also configure those properties. I will soon write about how to configure the properties (e.g., whether the property should be writable or if it should be configurable, and etc.), but we can also define "getter" and "setter" on object's properties. For example, "setter" could be useful in a scenario where we would want to do some processing on the property before setting its value to something and same goes for the "getter". So, there are two ways to go about it. One way is to define "getter" and "setter" in an object itself, e.g.

Another way is to define "getter" and "setter" by using/calling the built-in Object.defineProperty (object, property, descriptor_object). Object.defineProperty method takes three parameters:

  • Object: The object whose property we want to define or configure. 
  • Property: The property on the object that we want to define or change. 
  • Descriptor object: Descriptor object allows us to configure the property and it has following attributes, namely; writable, value, get, set, configurable, and enumerable. I am going to write more about it a little later. 


 So, we can define both "getter" and "setter" using Object.defineProperty like the following:

So that's about it, for now. Let me know what do you think. Please let me know if there are any other ways to achieve the above (or, even, please feel free to suggest corrections in this post--thanks in advance).


Defining and Configuring Object Properties in JavaScript

So JavaScript has made it possible for us to interact with property attributes. Now we can make an object property enumerable, set it to read only and even make it configurable. This is possible because of property attributes. 

Object properties and property descriptor

So object has properties and we can set the state of those properties using fields (e.g. value, writable, enumerable, get, set, and configurable) of property descriptor object. We can see how we can access fields of property descriptor object below:

So here is an object:

Let's say we wouldn't anyone to delete the chasis_no property or may be we would want engine_no as just a read-only property. By the way, all properties of an object are both enumerable and configurable by default. JavaScript allows us to interact with object properties and we can do that by calling Object.defineProperty method which takes an object, property name we want to interact with and property descriptor object as parameters. 

Data and accessor properties

There are data properties and accessor properties. Data property is a value which can be read, written to, configured and and even enumerated. Whereas accessor properties define get and set functions that are called when property is read or written to, respectively. If we look at the following code:

'wife_enabled' is the data property whereas 'name' is being used as the accessor property. 

So there are two kinds of property attributes, namely; data properties and accessor property attributes. JavaScript allows us to configure properties, let's consider few scenarios:

  • A JavaScript programmer may want to control whether a property of a certain object should be deleted or not. For example, he may not want to allow deletion of a certain property. 
  • Let's say a User class is defined with two properties; username and password. Furthermore, let's say I don't want to make the password property enumerable, that is, I don't want the password property to appear when someone is enumerating User properties.
  • Let's say a Car class has a property named chassis number and we want to make it a read only property, i.e., no one can write it. How do we go about it?

Using property attributes to change state of properties

We can make all this happen using property attributes (and they can be set using property descriptor object and we will shortly see an example), and those are:

  • [[Enumerable]]: Allows us to make a property enumerable, i.e., if it's false, then this property won't show up when the object's properties are enumerated using a for-in loop. Its default value is set to false.
  • [[Configurable]]: It defines whether the property can be deleted or if it can be changed to accessor property . If it's set to false, then property cannot be deleted and it cannot be changed to accessor property. Default value of this attribute is set to false.
  • [[Value]]: The actual value of property is stored in this. Default value of this attribute is set to undefined.
  • [[Writable]]: Allows us to configure whether we can write to a property. If it's set to false we cannot alter the property's [[Value]] attribute. So, for example, if we want to create a read only property we should set writable attribute to false. Default value of this attribute is false.
  • [[Get]]: This contains the Getter function which you can define to do some processing while reading the value. [[Get]] is exclusively used for accessor properties. Default value of this attribute is undefined.
  • [[Set]]: As the name suggests, this contains the Setter function which you can define to do some processing while setting the value. [[Set]] is exclusively used for accessor properties. Default value of this attribute is undefined.

So, both [[Enumerable]] and [[Configurable]] are common to both data and accessor properties, whereas, data properties have two additional attributes, namely; [[Value]] and [[Writable]]. Accessor properties have two more attributes and those are [[Get]] and [[Set]].

Interesting, JavaScript allows us to configure all these property attributes using a method named Object.definedProperty(object, property_name, property_descriptor). So the first parameter is the object, second is the name of the property we want to configure and third is the property descriptor that contains the values of enumerable (configures the internal property [[Enumerable]]), configurable (configures the internal property [[Configurable]]), value (configures the internal property [[Value]]), writable (configures the internal property [[Writable]]), get (configures the internal property [[Get]]) and set (configures the internal property [[Set]]) as shown below.

Hopefully, the following code will clear things up:

There, however, is one caveat we should keep in mind. If we don't specify the value of property attributes when we are trying to configure a property then they default to false. So let's look at some code.

In the above example, we have not given the values of writable, and configurable attributes when we called Object.defineProperty() so they will default to false. So this is something important which needs to be kept in mind while configuring property attributes.

References:


    Specifying prototypes using object literals in JavaScript

    In JavaScript, there are different ways to create an object. Once the object is created we can check its type by:

    our_inst instanceof InstType


    If we want to know about the function that created the instance we can do following:

    our_inst.constructor == FunctionThatCreatedIt

    So "constructor" is a property defined on the Property object and it always points back to the function that created the instance. If the object is created using object literal then following will return true because the literals (i.e. var our_inst = {}; ) point back to Object.

    our_inst.constructor == Object; 

    If the object is created using a constructor function e.g.

    function Browser(name, version){
      this.name = name;
      this.version = version;

    }

    Then following will return true (as chrome.constructor should point back to the Browser):

    var chrome = new Browser("Chrome", "1.0.3");

    alert(chrome.constructor==Browser);


    So far so good. Now inheritance in JavaScript works using a "prototype" property, which in itself is an interesting topic. If you add properties to the "prototype" then it will be accessible to all instances of that type. We can add multiple "prototypes" to our type like following (and whatever we add to the prototype, it will be available to all instances of Browser type):


    Browser.prototype = {

      renderText: function(){

        return alert('Rendering Text...');

      },

      renderCSS:function(){

        return alert("Rendering CSS...");

      }

    }; 


    But now if I do the following, it will return 'false':

    alert(chrome.constructor==Browser);


    Which looks quite strange, no? When I came across this I was not sure what happened there. So there are few things at play here, let's look at them one by one.


    1- Every function in JavaScript has a property named 'prototype' which points to the Prototype object. The Prototype object has a property named "constructor" which always points back to the constructor function that created the instance. 

    2- Now if you try to define the prototype like 

    Browser.prototype = {};

    Then, what happens is that we have assigned an object literal to Browser's prototype. So the "constructor" is defined on the Prototype object but now we have assigned an object literal to Browser's prototype and object literal's "constructor" point backs to "Object". Since the object literal we assigned doesn't have any 'constructor' property so it defaults back to the Object. So that's why following outputs "Object" as opposed to "Browser".


    alert(chrome.constructor==Browser);


    To remedy this situation we can explicitly set the 'constructor' property inside the object literal like:

    Browser.prototype = {

      constructor: Browser,

      renderText: function(){

        return alert('Rendering Text...');

      },

      renderCSS:function(){

        return alert("Rendering CSS...");

      }

    }; 

    I am no JavaScript czar, I just love learning about it. If you find any mistakes or errors, please reach out to me so I can correct those. Following Gist contains all the corrected code.



    Book Review: Truth Always Prevails: A Memoir (by Sadruddin Hashwani)

    So I just finished reading this book, which is written by Sadruddin Haswani who is a prominent businessman in Pakistan. Reason I read this book was to learn from a successful businessman. Here is the summary of things I learned from the book:

    • His first business was to help his brother in law in one of his businesses. That was his first business and he worked really hard at it. Profit margins were low and there was a lot of inter-province travel involved. He was working on this relentlessly, even then he had this "growth" mindset as he wanted to grow even more and never settled whenever he reached a certain milestone. He setup goals and he wanted to achieve those no matter what. He always he had this desire to improve his performance. Unfortunately because of some personal issues he had to quit this business and leave everything he built. That was kind of sad. 
    • His next business was to sell bailing hoops. Very soon in this business he realized that he needed to do something unique to stand out from the rest. He improved the payment cycles and also focussed on quality. He, then, diversified into different other products. He always wanted to know more about this business. He also worked on accumulating cash. Then, a very big order came knocking his door to export cotton to Russia. Banks weren't willing to finance so in order to fulfill the order he partnered with a company. 

             Also, he realized that he needed to build his business on few foundations e.g. a)- low profit b)- fast delivery and c)- low expenses. For his customers his reputation and price were important to him. He worked very hard at this business e.g. he would start as early as a 8 am and stay till night. 

    • He became the number 1 exporter of cotton. There was a point when he needed to pay a big amount and he felt totally helpless but then a manager of a Bank of China helped him with the payment. Probably that is a true reflection of "where there is a will, there is a way". 
    • Then because of his reputation Louis Dreyfus Group started buying rice and it proved really profitable for his other businesses. Later, he ventured into building hotels all over Pakistan. He even bought a hotel in US at some point. Rest is history.


    From what I can tell after reading this book, as a business man I find him hard working, intelligent, determined and a smart guy. He also faced a lot of political pressure but he stood his ground. He didn't have a degree in business administration yet he bootstrapped multiple businesses in multiple industries which I find really amazing. 

    Cars with an Information Dashboard (to help other drivers)


    Driving is something I really used to enjoy. Not sure what happened but I find it little stressful now. I live in Lahore and traffic here is not easy. It gets particularly hard around noon (time when schools or offices are closing). 

    At times, people need to turn right but they switch on the left indicator. Other times, people will come all the way from left to suddenly turn to right. You may also find people suddenly slowly down on a quite road when it's not really needed (when you overtake them you see that the driver was using cell phone, hence the slowing down). I have also seen people frequently changing lanes and that's very dangerous if you do that without giving any indication to people already in the lane. You also see come across impatient overtakers who start showing you headlights as soon as they are behind you. People also overtake from left. Not only that it really hurts when you park the car in parking only to come back and see that someone has parked a car right behind you and he's not in the car. Bummer!

    So I was driving today and a thought came across my mind. What if we have a dashboard which is visible on mirrors (may be on a rare window) and other people can see some useful data in there? So may be a dashboard can contain the following:

    • It states that the data represents snapshot of last 30 days.
    • It can show some graphs and things like
    • 5 wrong overtakes
    • 5 Overspeed tickets
    • Parked wrong 2 times this month

    Of course we can write more there but probably the most critical items show up at the top. Arguably, this help in following ways:

    • It may help other drivers to make better decisions.
    • So when drivers start making better decisions it may help the flow of traffic.
    • So when drivers take better decisions and flow of traffic is improved then we can hope that we see less traffic accidents on the road.

    There is a chance that too much information can increase the cognitive load on the drivers' mind. So one way to reduce the cognitive load is that the system only makes the dashboard visible when it senses that driver is trying to do something which is closely related to some of the mistakes he did recently. e.g.

    • If driver has been getting speed tickets then whenever a driver crosses the limit the dashboard should appear. 
    • If driver takes too many wrong turns then whenever driver gives a right indicator and if car is going on right then may be it's time to show the dashboard. Trick will be to show it as soon as possible.

    I am not sure about how practical this is but it was just a thought when I was driving back home. 


    Note:

    Thanks to some friends for reading the drafts of this article.

    Book Review: Daily Rituals: How Artists Work

    So after a long time I have finally been able to finish a book. I really want to read more books this year. So "Daily Rituals: How Artists Work" is a great book. I really enjoyed reading it. Highly recommended.

    It contains some details on the daily routines of various famous writers, music composers, painters, scientists, poets, filmmakers, sculptors and etc. Here are the key takeaways from the book (off the top of my head):

    • Almost everyone famous had set aside a solid chunk of time in a day totally devoted to work. So much so that some people didn't like any interventions around that time. I recall, from the book, that many people used to work without any breaks from 7 am to 1 pm. For example, Francis Bacon woke up very early and worked continuously till noon and that was his daily routine. Some preferred to work at night, for example, Thomas Wolfe liked to work all night. Some wanted no interruptions at all it's written about Thomas Mann; "Then, at 9:00, Mann closed the door to his study, making himself unavailable for visitors, telephone calls, or family. The children were strictly forbidden to make any noise between 9:00 and noon, Mann's prime writing hours. "

             And another one is Gustav Mahler (and Alma was his wife):  "Then he shut himself inside to work. Meanwhile, Alma's job was to make sure that no sound carried to the hut during Mahler's working hours. She refrained from playing the piano, and promised the neighbors opera tickets if they would keep their dogs locked up. "

    • Some famous people even had a social life. I had this perception that probably they worked all the time, which isn't true. They focused and worked in a solid chunk of time without any interventions but some of them also left time for family and other social duties.
    • Some even carved out time daily for walk or nap (or even a swim). It sounds like a good idea to take break from work and let your work do some work in the background within your brain. Danish philosopher Soren Kierkegaard always did two things daily; walking and writing. He always had his best ideas on a long walk. Gustav Miller used to go for a swim daily. Richard Strauss would go on a long walk after having tea at 4 pm until 6 pm daily. Carl Jung would go on for long walks daily in the hills. 
    • I was relived to know that some of the great minds also fought procrastination. But I think most of them fought it with discipline. For example, Thomas Mann made a point to work from 9 am to noon on daily basis without any interruptions. Gustav Mahler worked from early morning to midday on daily basis. 
    • For some people external conditions were important too. Some people ate same lunch every single day. Beethoven wanted exactly sixty coffee beans per cup in the morning. Morton Feldman wanted the right pen, and a good chair. 
    • Almost all of them really liked working. They were passionate about their work. Gustave Flaubert noted (as given on pages 32 and 33 of the book) "Sometimes I don't understand why my arms don't drop from my body with fatigue, why my brain doesn't melt away. I am leading an austere life, stripped of all external pressure, and am sustained only by a kind of permanent frenzy, which sometimes makes me weep tears of impotence but never abates. I love my work with a love that is frantic and perverted, as an ascetic loves the hair shirt that scratches his belly. Sometimes, when I am empty, when words don't come, when I find I haven't written a single sentence after scribbling whole pages, I collapse on my couch and lie there dazed, bogged down in a swamp of despair, hating myself and blaming myself for this demented pride that makes me pant after a chimera. A quarter of an hour later, everything has changed; my heart is pounding with joy.

             He also wrote, "work is still the best way of escaping from life!"

    Hello world ;)

    Hello, everyone. This is your host Waqas. I am based in beautiful city of Lahore, Pakistan. I will be writing my thoughts on quite a few things. I am sure I will make friends and learn from people around the world ;)


    Stay tuned ;)