JavaScript

JavaScript Properties Example

Properties are one of the most basic Javascript notions. Basic to the point that they are more often than not overlooked in the language’s literature. However, it’s crucial to know and study them even for those who only want to have even the most elementary knowledge about JS.

1. What are Properties exactly?

According to the official definition in the Javascript documentation, an object having a property means having an “association between a property name and its value.” Though, if you want an even clearer version of that definition, think of properties as the building blocks of an object, as these two concepts (and variables too) are very deeply interwoven with each other.

You can even think of properties as objects in and of itself, as they not only have a string for a name but also a set of attributes assigned to them.

We can divide properties in different types based on different qualifications. For starters, what we defined above are called direct properties as there is a direct association between a property name and it’s value. Except for that we have properties whose values are assigned indirectly through getters and setters which are simply functions associated with property values.

Moreover, a property can be own or inherited, based on where it is contained in the prototype chain. While the first ones are contained directly by the object, the second type can be contained by one of the other object whose child our object is.

Also, we divide properties into named and internal based on whether they are or not a part of ECMAScript. We’ll take a short look on these later.
 

2. Property Attributes

There are a number of attributes assigned to a property depending on the type it is, but there are two that are common for each one. These two are Enumerable and Configurable. When the first one is set to the boolean value TRUE, that means that the property can be enumerated using a for...in enumeration, while when the second one is set to FALSE it prevents the property from being deleted or modified in any way. If Configurable has been set to FALSE once, it cannot be reversed, and also you can’t change the other properties (except setting Value and Writable from true to false, the vice versa not-withstanding).

2.1 Named Properties

We mentioned that properties are divided into named and internal. Named properties are further divided into named data properties and named accessor properties. Let’s take a look at each one separately below.

2.1.1 Named Data Properties

A named data property means having a property with two very important components: a name and a value that is directly associated to it. Additionally to the general attributes these types of properties also have two other attributes, which are Value and Writable. The first one specifies a values retrieved when reading the property, while the second, when set to FALSE, prevents the internal method Put from changing the Value attribute of the property. Take a look below:

properties.js

 
Object.defineProperty(this, "MYVAR", {
  value: 100
});

console.log(MYVAR);  // result: 100

What we have done here is just define a named data property, giving it a value of 100. If we try to later change this value or completely delete the property we will be presented with an error, since by default we would have [[Writable]] = false (which prevents rewriting) and [[Configurable]] = false (which would prevent deleting of otherwise changing it). The default data property attributes would be these:

properties.js

 
var defaultDataPropertyAttributes = {
  [[Value]]: undefined,
  [[Writable]]: false,
  [[Enumerable]]: false,
  [[Configurable]]: false
};

2.1.2 Named Accessor Properties

While Named Data Properties were composed by a name and a value associated directly to it, a Named Accessor Property is formed by a name and one or two accessor function which would be getters or setters associated indirectly to it.

In this case, except for the two general attributes, there are two more added, which are Get and Set. Get is a function object which is called every time for retrieving indirect value related with the property name, while, understandably, Set does is the function object who does the setting of the value associated with the property name. Take a look:

properties.js

 
var myvar = {
 
  get wcg () {
    return 20;
  },
 
  set wcg (value) {
    console.log(value);
  }
 
};

var defaultAccessorPropertyAttributes = {
  [[Get]]: undefined,
  [[Set]]: undefined,
  [[Enumerable]]: false,
  [[Configurable]]: false
};

This is how we have defined a named accessor property and below there are the default values of it’s attributes. If we tried to overwrite wcg‘s value, say using this line of code myvar.wcg = 100;, we wouldn’t be able to do it, since the Set value is empty.

2.2 Internal Properties

Objects can have a number of internal properties which are part of the implementations and not accessible with ECMAScript programs. These properties are enclosed by double square brackets (i.e [[Writable]]). For these properties there are a number of extra attributes except for the two general ones.

Some of the most used ones are:

  • [[Prototype]] – it represents the prototype of the object
  • [[Class]] – represents the type of the object such as Array, String, etc.
  • [[Get]] – method that gets a property’s value
  • [[Put]] -method that sets a property’s value

It is important to note that the [[Get]] you see here is not the same as the data attribute in named accessor properties, as this is a method that calls the Get property, with [[Put]] having the same effect on the Set property.

3. Property Accessors

Property Accessors are what we use to get access to an object’s properties. This can be done in two ways: by using the dot notation and by using the square bracket notation. The syntax for both is fairly easy:

syntax.js

 
object.property
object["property"]

This is how we use the dot notation to access a property in real code:

properties.js

 
person.firstname + " is " + person.age + " years old.";

What you have to keep in mind here is that the property name has to be alphanumerical, and not start with numbers, underscores or dollar signs as the code would be invalid. Below you can see how we use the square bracket notation to do the same job, albeit a bit differently:

properties.js

 
person["firstname"] + " is " + person["age"] + " years old.";

person[firstname] + " is " + person[age] + " years old.";

Both ways shown in the code snippet above are valid. This method also doesn’t impose on your code the limitation presented by the dot notation about your property not starting with a number, underscore or dollar sign. In this case, your property can be whatever.

4. Defining Properties

While explaining all of the above, you might have noticed that we used different methods to define a property. There are lots of ways for you to do this, but 5 are the most famous among programmers:

  1. dot notation
  2. square bracket notation
  3. leaving out the var keyword
  4. Object.defineProperty()
  5. Object.defineProperties()

This is how we would use the first three methods to define a property, as the two last ones will be explained to you in more detail:

properties.js

 
//dot notation
window.foo = 'hello';
 
//subscript notation
window['foo'] = 'hello';
 
//leaving out the var keyword
var bar = function() {
    foo = "hello";
}

4.1 Object.defineProperty()

Object.defineProperty() is a method that defines a new property directly into an object or modifies an already existing one and returns the object. It’s syntax would go like below:

syntax.js

 
Object.defineProperty(obj, prop, descriptor)

As you see, this method takes three arguments, the first one being the object on which we want the property to be defined/modified, the second is the property in question and the last is the property’s descriptor which is the set of a property’s attributes and their values.

By default the values of these properties that are created or modified are deletable, enumerable, and their values may be changed later on. However, these attributes’ values can be changed later on.

4.1.1 Creating Properties

When the property specified in the Object.defineProperty() method does not previously exist, it is created into it. The descriptor can be left unprovided (or parts of it unspecified) and the default values will be provided instead. The code would go like below:

properties.js

 
var myvar = {}; 

Object.defineProperty(myvar, 'a', {
  value: 100,
  writable: true,
  enumerable: true,
  configurable: true
});

Can you guess the type of the property a based on the code above? You’re right, it’s a Named Data Property. Not much would change for the other types though.

4.1.2 Modifying Properties

Modifying properties can turn out to be a bit more tricky than creating them, even though it’s no rocket science. The method will attempt to modify the specified property in case it already exists. However, the attributes Writable, Enumerable and Configurable limit this. Take a look and let’s explain from there:

properties.js

 
Object.defineProperty(o, 'a', {
  value: 100,
  writable: false
});

As you see, the attribute Writable is set to false, so any attempt at modifying the value would be moot. In case that Enumerable was the one set to false, the property would give us the opportunity to reassign a different value, but the property wouldn’t turn out in for...in cycles of enumeration. If it was Configurable the attribute which was set to false, we would not be able to modify the property’s attributes, except for Writable.

4.2 Object.defineProperties()

Object.defineProperties() is a method that works similarly to the one above, only it adds many properties at the same time. However it’s not used very much as it has a very major catch: It only works on Chrome and Safari. You’d be able to use it like below:

properties.js

 
Object.defineProperties(window, {"foo": {value: "hello"},"bar": {value: "goodbye"}});

Now you’re fully able to understand and use Javascript Properties in detail.

5. Download the source code

This was an example of Properties in Javascript.

Download
You can download the full source code of this example here: Properties

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button