Anatomy of a ban

A government puts regulatory authorities in place so that activities can be regulated to benefit the public, protect the environment, and prevent market failure. Some of our regulatory authorities have been banning things right and left. It is important to note that banning things, without thinking through their repercussions, can have harmful economic and psychological consequences.

There are five things to consider in terms of the economic consequences of bans. First, though regulatory authorities are sometimes put in place to prevent market failure, ill-planned regulations can actually cause such failure. Assume there is a certain problem (eg, overpopulation) that a government wants to address, and entrepreneurs come up with products (eg, contraceptives) to tackle the problem. A ban on advertisement of such products will discourage future entrepreneurs from making those products in the long run.

Now, although the government admits that there is a problem, and there is also ample demand for the product which will solve it, putting a ban will, in the long term, reduce the number of suppliers of that product – thus eventually causing market failure, or at least defeating the policy of the government.

We should also reflect on whether an advertising ban restricts promotion on all media. Even if regulators ban advertisements on media over which they have control, entrepreneurs will find alternative media through which to advertise their products. For example, if a product is banned on all TV channels, an entrepreneur can still advertise a product (globally) on the internet, which regulators do not control. Hence, not only will people within the restricted locality still be able to see those advertisements, but more people around the world can see them as well.

Second, it is important to question if, since regulators are so entrenched in the problem to which they are a solution, they unwittingly perpetuate the problem? This observation comes from ‘Shirky’s principle’, which states that “Institutions will try to preserve the problem to which they are the solution”. Further, regulatory economics tells us about ‘regulatory capture’, which happens when instead of protecting public interest the regulator is more keen to protect the commercial or political concerns of special interest groups. When the interests of a special group take priority over public interest, society is harmed and the purpose of having a regulator is defeated. So the government needs to put in place mechanisms to check if regulatory authorities are falling prey to ‘regulatory capture’.

Third, bans sometimes disrupt the economic activity of a nation. For instance, in March 2015, when India placed a ban on beef, it led to a loss of income for many people. Farmers found it difficult to find buyers for their cattle. Most of the farmers resorted to taking loans to cover their major expenses. It was also reported that many related industries were also severely affected due to this ban. Bans that are imposed without addressing the real social taboo or any due cost-benefit analysis can lead to losses than benefits.

Fourth, bans may also increase the cost of doing business and the cost of products in a country.

Bans have psychological repercussions as well, as described by Adam Grant (organisational psychologist and a professor at Wharton School of University of Pennsylvania), that can cause them to backfire. First, there is the issue of ‘reactance’. According to Grant, “When someone discourages you from doing something, you often feel that your freedom is being threatened, which motivates you to regain choice and control by doing exactly the opposite.”

Bans have an inbuilt self-destructive mechanism. Simply, if something is not allowed to an individual, it becomes all the more appealing to him or her. Hence, this then provokes people to doing it even more than before. For example, banning a book or a product can tremendously generate a great deal of free publicity.

Second, there is the issue of ‘rebound’, the idea that when someone warns you not to think of something or if your thoughts are being suppressed, your mind has a tricky way of thinking more about it. For instance, if someone asks a person particularly not to think about a certain term or an idea they tend to think more about it. A very simple daily life example of rebound effect is that of dieting. When a person is on a strict diet and try to suppress thoughts of sugary products like chocolates and candies, they end up consuming it even more. So ‘rebound’ actually makes a person more prone to thinking about that very thought which is prohibited.

Last, we may encounter a problem of ‘curiosity’. This is the principle of reverse psychology whereby people become intrigued when something is not allowed and therefore investigate. Adam Grant notes in one study, “psychologists asked 159 people if they had ever deliberately tried to get people to do something by recommending the opposite. More than two thirds generated a convincing example, and reported using reverse psychology an average of 1-2 times a month, with relatively little difficulty and high effectiveness.”

Most people react differently when bans and regulatory bans are enacted, and bans hardly fulfil their purpose. We saw an example of this when Indian films and TV shoes were banned in Pakistan . People could not resist the temptation and started watching shows and movies online, and piracy became even more rampant.

Bans are a growth industry in Pakistan; they give an illusion of power to people. Behind this illusion of power, regulators think that bans are going to solve problems. However, it is important that both economic and psychological effects are taken into account for bans to be productive. It is ill-planned bans that wreak havoc.


This opinion was published in The News on 07th August, 2016. 

Urban Sprawl and Pakistan


(co-authored with Dr. Nadeem Ul Haque)

Cities are often a reflection of their zoning codes. Unfortunately, in Pakistan citizens never have any say in how their cities and towns are designed. The width of our streets, height of our homes, size of building lots, amount of space reserved for pedestrians, even the reason we cannot operate a donut store in our garage are all dictated by zoning regulations.

Bad zoning codes result in sprawl – and sprawl make societies worse off. According to urbanist Charles Montgomery, sprawls result in bad health, little trust and low social capital. Moreover, people living in sprawls are less likely to volunteer, vote and even join political parties. Therefore bad zoning codes result in miserable communities and they are affecting our cities too. But how do our zoning codes and misuse of land result in sprawl?

First of all, our zoning codes discourage mixed-use and high-rise development. There are no apartment buildings with shops and offices near even within such buildings. Most well-designed cities that we appreciate are based on mixed use.

Our zoning codes also mandate that for new housing projects developers buy land in hundreds of acres. This results in sprawl primarily because hundreds of acres are usually not available within a city. It also encourages big investors who can afford that much land, thus reducing competition. An aside, it reduces the availability of fertile agricultural land.

The fact that the government owns large chunks of prime urban land reduces the supply of available land within cities, which in turn also leads to sprawl. There is a huge opportunity cost of the inner city land that government holds to provide its officials with plush housing and unnecessary offices. A Planning Commission study showed that investment could increase by 50 percent of GDP over 10 years – if this land were made available for mixed-use, high-rise development.

Our traffic management focuses on building roads and corridors for cars. The use of cars has been facilitated at the expense of other forms of transport such as bicycles, walking, taxis and even buses. With cars so subsidised, it is not hard to see why the sprawl is spreading.

In most cities, the planning process often has no zoning for the poor. Apartment buildings are seriously discouraged through planning permissions and high fees for commercialization. For some reason our planners think of apartments as commercialisation, and so poor housing is taxed heavily.

Rich housing – single family homes with highways leading to them – are encouraged. Planners even forget to cost the infrastructure required by such housing. Pipes, electricity roads etc – eventually all this expense is borne by the poor of the city.

Excessive focus on form over function has incentivised inefficient use of land to attract customers, and inefficient use of land leads to sprawl. As consumers we have to pay more attention to form than aesthetically appealing architectures because empirical evidence shows that though we place more weight on physical features, eventually we might be less happier in physically appealing buildings. A study at Harvard by Elizabeth Dunn had students select their houses for their subsequent school years; there was a forecast among students that they would be happier in beautiful houses than less appealing ones.

However, after students settled in these houses their happiness was determined more by social features and the quality of relationships they developed in those houses. Students ended up being happier in architecturally miserable houses because they had better social features. Dunn noted: “Participants overestimated how happy they would be in desirable houses and how miserable they would be in undesirable houses. Our results suggest that forecasters may have erred by focusing on physical features such as location while virtually ignoring the quality of social life in the houses.”

We can try to fix our land use and zoning laws to discourage sprawl and thereby construct more equitable, vibrant and productive cities.

We need to tweak our zoning codes so we can build high-rise and mixed-use property to create more spaces for people in a more concentrated area. We need to think more about building vertically rather than horizontally.

Zoning laws should encourage competition and also mandate socially-responsible housing. Large investors who buy the hundreds of kanals mandated are keen to maximise their profits, so their plans price out low-income households. This results in illegal housing and housing schemes deprived of the basic necessities of life. Zoning codes in some developed countries mandate social housing that accommodates people from low-income background. This helps mitigate sprawl and fosters tolerance, trust, equality and care.

Our zoning codes should encourage urban development with high FARs (Floor Area Ratio). According to a study, on urban land and housing markets in Punjab by David Dowall and Peter Ellis, restrictive FARs are constraining urban density in Punjab. The study also notes that low FARs result in high land prices, a reduction in agglomeration benefits, lengthier commutes, limits formal housing (thus pricing out poor), and affects low-income most.

Zoning codes shouldn’t incentivise parking. Currently developers are mandated by law to provide parking spaces – no matter the type of building. Incentivising parking means we are encouraging developers to create commercial and housing projects farther away from urban centres and encouraging people to shop farther away from home.

Both of these lead to sprawl. In addition, according to economist Donald Shoup, “minimum parking requirements subsidize cars, increase traffic congestion and carbon emissions, pollute the air and water, raise housing costs, exclude poor people, degrade urban design, reduce walkability and damage the economy.” More land for parking also means less land for housing, shops, libraries, schools and hospitals.

It is important to understand where we are headed. All major cities like Karachi and Lahore have master plans. Though inhabitants should have the largest say in shaping cities, their input is never incorporated in these master plans. Our zoning codes should address senior citizens, persons with disabilities, as well as matters of public bike sharing, low-income households and the fact that real-estate developers should be mandated to give back to society in the of schools, libraries and hospitals.

Whenever we move into a particular housing society there is only one zoning law available; there have to be alternatives that prevent or repair sprawl. We need to correct our zoning codes by looking at other poorly-designed modern cities are and not repeating their mistakes.


This opinion was published in The News on 19th July, 2016. 

Case against privatisation in Pakistan

Feisal Naqvi concluded in The News that state-owned enterprises (SOEs) fail primarily because of speed and accountability. If this argument is applied to our SOEs, then almost all of them – given their performance – should be privatised to increase speed and accountability, but this would not be very realistic.

Also, the case is weak for a new private buyer to purchase a public asset, because that buyer would have to deal with public departments that are slow and rarely held accountable, which would impede growth.

SOEs have thrived in some economies; one cannot dismiss SOEs altogether. According to a report by PricewaterhouseCoopers, the share of SOEs among the Fortune Global 500 has grown from 9 percent in 2005 to 23 percent in 2014. Furthermore, the top eight countries with the highest SOE shares accounted for more than 20 percent of the world’s trade.

A major proportion of the SOE growth worldwide is due to the Chinese SOEs. Three Chinese SOEs consistently made the top ten since 2010. Chinese SOEs have roughly $17 trillion in assets and employ more than 35 million people. Factors like attracting top talent, foreign investment, linking executive’s compensation to performance, globalisation and choosing a hybrid structure of corporate governance contributed to their success.

Chinese SOEs have established a hybrid structure through independent management akin to a private corporations, while deriving their financial power from the government. Like the SOEs here, Chinese SOEs face challenges from both the bureaucracy and political interference. The Financial Times reported that in 2004, the CEOs of several Chinese telecom companies were shifted overnight without any prior notice. Even in face of these challenges, Chinese SOEs have posted amazing results.

Another amazing example can be found in Singapore. Singapore manages a portfolio of SOEs through an investment company called Temasek Holdings, whose sole shareholder is Singapore’s Ministry of Finance. Temasek has managed a net portfolio of $177 billion, as of March 2015. Temasek’s companies are managed without government involvement; instead, Temasek provides flexibility by allowing each board to dictate its own terms for each portfolio company. This method of management has proven so successful that even China wants to imitate Singapore’s strategy on a larger scale by 2020.

Both Chinese and Singapore SOEs have handled the issues of incentive and reinvention. Though privatisation is a prudent way to eliminate budget deficit, reduce the size of government and increase public service delivery, it has not worked everywhere. PTCL’s example supports this assertion, because its profits and service delivery did not significantly improve after privatisation. Many academics have provided helpful critiques of privatisation. Some of the issues that Paul Starr, professor of sociology and public affairs at Princeton, has raised should be considered.

First, the message that privatisation sends is demoralising. This message is that whenever we face a problem, we should sell an asset instead of fixing it with good intent. This tends to discourage citizens by showing them that the government is either incompetent and cannot fix its own institutions or lacks the initiative to fix them. Moreover, when the government consistently chooses to sell its assets to the private sector, it is essentially making a ‘buy vs make’ decision. If buying were the way to go in the face of trouble, then no large corporations would exist.

Additionally, the continuous sale of our assets may make us less of a nation. Starr has argued that the sale of SOEs would decrease accountability and reduce public debate, ultimately reducing the public’s interest in the country’s businesses. Starr compares the suggested treatment of the government’s assets to a family’s consideration of their food as the nourishment necessary for survival; in other words, instead of thinking about its institutions as a subsidy, the government should consider the success of its institutions as integral to the country’s survival.

Some supporters of privatisation argue that it will decrease the size of the government. However, lobbyists in the private sector aggressively lobby for increased public spending because that is how they make money. With more resources, private companies use their influence to secure government contracts. With increased public spending still an issue, the size of the government is unlikely to be reduced.

Furthermore, there is a cost to the citizens when the government does not fix the issues with its institutions. Both our education and health systems are examples of the government’s lackadaisical attitude toward problems in the public sector. Instead, the private sector has created a wealth gap. Since the private sector can charge whatever it wants for the services it provides, only the wealthy are able to benefit from them and those who do not have sufficient income cannot obtain quality care. This gap has diminished the access of the poor to quality services. The focus cannot merely be on privatisation; we must focus efforts on improving public services in order to increase public access to quality services.

Proponents of privatisation also argue that converting public sector services to private ownership will give the private sector the freedom to perform more efficiently and force companies to provide better customer service. Despite the benefits, it is important to note that the private sector is driven by its own interests and may not consider public interest when making decisions.

Moreover, it is assumed that buyers will pay more for an entity than what it is actually worth because the private sector buyer expects greater revenues from the sale. We should remember that potential buyers usually pay less than the asking price, when the entity needs restructuring. At times, it makes more sense to sell an entity after doing some restructuring than it does to sell it haphazardly.

We must make an attempt, with good intent, to improve an organisation before throwing in the towel. As business author Guy Kawasaki said in ‘Rules for Revolutionaries’, “create like a god, command like a king and work like a slave.” It seems we believe in the first two, but we fall short of the third. In order to truly improve our institutions, we need to put in the work. If we put in the necessary work, we wouldn’t need the private sector to rescue our institutions; we could rescue them on our own.

This opinion was published in The News on 13th March, 2016. 

Real cost of car-centric cities (in Pakistan and elsewhere)

(co-authored with Dr. Nadeem Ul Haque)


DRIVING a car takes a personal, societal, financial and environmental toll. Since the cost of cars is high, we should not support development projects (roads, flyovers and bypasses) and policies (misuse of urban land and poor zoning) that subsidise and necessitate their use. Too many automobiles make us unsafe, unhealthy, unhappy, unfriendly, and, in general, miserable as a society.

Among the costs that cars exact is that on our personal health and safety. Excessive driving causes stress and ill health. Gallup and Healthways surveys have determined that longer commutes lead to more chronic pain, higher cholesterol and general unhappiness in drivers. Moreover, driving everywhere leads to obesity; in the US alone, the cost of obesity in 2008 was $147 billion.

Secondly, cars have a societal cost: increased traffic decreases social capital. Donald Appleyard, in his now famous 1972 study, found that residents of high-traffic areas have fewer friends and acquaintances than residents of light-traffic locations. Traffic also causes noise pollution, which makes us more intolerant of each other.

Thirdly, cars cost us a great deal financially. There is the initial, upfront payment. Then we have to pay for financing (and hidden fees), car maintenance, parking, and fuel. According to some back-of-the-envelope calculations, people in Lahore pay Rs24bn per year for fuel and oil changes. In addition, there is the expected cost of treating accidents and injuries that inevitably occur when we drive.

There is what we would call an opportunity cost as well. That is, with the money tied up in their cars, individuals could instead have invested in activities with greater returns or of higher value to their families (like holidays). Also, the overuse of cars costs us in terms of productivity when we are injured and cannot work, or are stuck in traffic.

Fourthly, an excess of cars adversely affects the environment. According to an online environment-cost calculator, we emit 1.2 pounds (0.54kg) of the greenhouse gas carbon dioxide by driving 1.5 miles (2.4km). Cars in Karachi alone are releasing roughly one million pounds of carbon every day, and 126m pounds of carbon every month.

Current policies enabling sprawl and subsidising high-speed traffic mean that people must own and use cars excessively. So what can we do?

As a guiding principle, we should keep everyone, not just the rich or people with higher incomes, in mind when we plan and zone our cities. As Mayor Enrique Peñalosa of Bogota noted, “Mobility is a right for all”. Peñalosa also noted that the modes of transport of the poor —walking, bicycling, and public transportation — need to be prioritised, as the bulk of the population uses them. We thus need to create more space for these modes.

First, we need to slow down cars and create more spaces for people. After the Second World War, Copenhagen had so many cars it came to a standstill. They prohibited cars in some areas, and the city thrived. Restricting the use of the car and slowing down the speed of vehicles is required to create space for people.

We can also charge a congestion tax, like Singapore and London, during peak hours in busier areas of cities. In addition, we can tax high-speed lanes and charge parking fees on a per-hour basis. These taxes can help reduce congestion. We also need to re-evaluate our zoning policies to discourage sprawl, and build mixed-use development, creating combined residential, office, commercial, and entertainment spaces within walking distance of each other.

Next we need to make more room for biking and walking, both currently hazardous activities. In cities around the world, separate bike lanes are being created; bike-sharing programmes are encouraged and sponsored by the corporate sector. We should also hold events to celebrate walking and biking like Ciclovía. Held in cities like Bogota and Medellin, Ciclovía is an event in which main roads are blocked on Sundays and public holidays and reserved for pedestrians and bicyclists.

Finally, we need to improve public transportation. Thanks to the emphasis our cities place on the use of cars, our public transport system has been allowed to erode. If we tax and regulate cars, we will have the funds and space required for public transport.

The famous Danish architect Jan Gehl said that if we make more roads, we get more cars; and if we make more space for people, we get more people, which in turn give us more vital and productive cities. When planning new development projects and designing urban policies, we should factor in the real cost of cars to an average citizen’s personal, social, and financial well-being, and to our environment. We should not repeat the mistakes that developed countries made in the last century in building their cities around cars.


This opinion was published in The Dawn on 16th May, 2016. 

Unreliable numbers in Pakistan's health-care data

FINALLY, after some ado, we have a document in the form of the National Health Vision (NHV), which identifies major problems in, and challenges to, our healthcare system. It also outlines our vision of how we plan to address those issues and challenges. One thing that will hamper, even damage, its execution is the unavailability of critical and reliable data. It is hard to believe that we will be able to do any serious planning or resource allocation to fix our healthcare issues without access to the correct data.

During an analysis, this author found data discrepancies in major government publications for healthcare data, namely the Pakistan Social and Living Standard Measurement (PSLM), the Pakistan Demographic and Health Survey (PDHS) and the Multiple Indicator Cluster Survey (MICS). It was found that, for certain healthcare indicators, data in one government publication differed for the same indicator in the same year from the data in another publication.

First, I found data discrepancies for an indicator named “deliveries with skilled birth attendants” between the PSLM and PDHS for the year 2012-2013. As per the PSLM, the deliveries with skilled birth attendants were 53pc in Sindh; as per the PDHS, however, they totalled 61pc in that province. In Balochistan, as per the PSLM, the proportion of births with skilled birth attendants was 35pc, but according to the PDHS it was 18pc in the same province.

According to a study by Jhpiego (an international non-profit health organisation affiliated with the Johns Hopkins University), skilled birth attendants can reduce newborn deaths by 43pc and prevent two-thirds of all maternal deaths. We can save more mothers and children if we allocate skilled birth attendants efficiently (which becomes even more important when resources are already scarce) based on correct and updated data.

Second, for the indicator “children (aged 12-23 months) fully immunised”, we again found discrepancies between the PSLM and PDHS, this time for the year 2006-2007 and for almost all provinces. For Sindh, the PSLM states that 65pc children were fully immunised, whereas the PDHS reports only 37pc children were fully immunised there. For Balochistan, as per the PSLM, the same indicator was 54pc, while the PDHS records it as being 35pc. According to the PSLM, 76pc of children in Khyber Pakhtunkhwa were fully immunised, while in the PDHS the figure was 47pc.

These differences are huge and baffling. It is inevitably low-income groups that suffer most when policymakers have inaccurate data for such important performance indicators. How can we ensure that our child immunisation rate is high in all provinces, in both rural and urban areas, when the data in major surveys does not match?

Third, for the indicator named “postnatal consultation”, for KP we found a discrepancy between the PSLM and MICS for 2008-2009. In MICS, the percentage of births followed by postnatal consultation was reported as 13, whereas in the PSLM survey, the figure was given as 23pc. Again, the difference is not small.

In our society, postnatal care is usually provided at home, and the idea of postnatal consultation is to ensure that new parents are given guidance according to evidence-based healthcare practices. The lack of good postnatal consultation can result in a higher mortality rate for both mother and child. The risk decreases as time passes, but it is imperative to receive timely consultation. Ineffective postnatal consultation may not promote, or may even discourage, breastfeeding, the absence of which can contribute to infections and malnutrition. It is unclear how any meaningful planning can be done to improve this indicator without access to the correct data.

These discrepancies are alarming. First, inconsistent data perpetuates confusion — which figure do we believe? This confusion can result in a misplanned policy, and even that one misplanned policy may have an undesired effect. The collectively dismal result of several such policies can take us many steps backward.

Second, these inconsistencies reflect a lack of rigour on the part of our government. If it is not careful about data acquisition, one is forced to infer that it is not serious about data-driven and evidence-based decision-making.

Third, incorrect data in government publications shows we still have a long way to go when it comes to competent data acquisition, so, sadly, we cannot yet turn our focus to the ‘analysis’ part and proceed to policy.

Fourth, most of the tall performance claims by the government are rendered insignificant when the underlying data is unreliable.

Such important healthcare indicators should not vary so much. Any researcher or policymaker who intends to carry out research or planning will use these government publications. Even the NHV cites the PSLM. Our expenditure on healthcare is already depressingly small, and it is going to hurt us if that small expenditure is used to plan and allocate resources using unreliable data.

This opinion was published in The Dawn on 29th September, 2016. 

Closer look at the Corruption Perception Index (CPI)

Few weeks back I published an OpEd in the Express Tribune. Transparency International publishes a corruption index named "Corruption Perception Index" and I just tried to highlight how it is calculated and what should people keep in mind before taking it into account. 

An excerpt:


In recent times, numerous corruption indices have been developed to measure corruption. One of the most widely used indices is the Corruption Perception Index (CPI) developed by Transparency International (TI). It recently reported that Pakistan has performed well in its CPI rankings. This certainly is good news and we must congratulate the people in power. But we need to question whether the CPI is a truly credible measure. Does it measure corruption correctly? We need to understand how such indices work.


Complete article can be read at http://tribune.com.pk/story/1048824/a-closer-look-at-perceptions-of-corruption/.

Deriving Y-Combinator in Scheme

Few weeks back I finished an amazing book called "Little Schemer". It is a very short book but it probably has the most profound effect on me when it comes to programming.

The authors took the Socratic style question/answer approach. It starts from the basics and slowly gears up to concepts like Y-Combinator and even the last chapter is about writing an interpreter.

Honestly, I had to go back and forth on understanding the Y-Combinator derivation but I really had an "Aha" moment when I finally got it. After reading up this book, I also read and understood Lambda Calculus e.g. the idea of using functions to represent arithmetic operations is really cool. 

Let's say we are using a programming language that doesn't support numbers or booleans. All that language provides is lambda. Because of church numerals, we can count, add, subtract, divide and even multiply just by using lambdas. Cool, no? Here is a paper in case you are interested in learning more about Church numerals.

So after reading the "Little Schemer", I set out on deriving Y-Combinator in Scheme and I made a PDF which is available below. I hope you enjoy it. Please feel free to let me know corrections or comments.


What causes violence?

I have been interested in economics and I read few papers on what causes mass violence. Recently, I wrote an Op-Ed in an English daily which can be read here: http://www.thenews.com.pk/print/97927-What-causes-terrorism.

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).