The ability to define objects in the form of literals is available in JavaScript, provides a shorter, more expressive and a less error prone way to write object definitions.
JavaScript objects can be thought of as hash tables, containing key-value pairs (resembling constructs that in other languages are called "associative arrays"). Values can be data of simple types or other objects - in both cases they are called properties. In addition, the values may be functions, in which case they are called methods.
Objects that you create yourself (in other words, user-defined language objects) are constantly available for change. Many of the properties of such objects are also editable.
You can start by creating an empty object, and then gradually add new functionality to it. Object Definition in the form of literals is ideal for creating such gradually expandable objects.
Take a look at the following example (you can change the code in the sandbox below and then press execute button):
In the previous example, we started creating an object from scratch, creating an empty object. Then we added a property and method to it. At the any stage of the program you can:
• Change properties and methods, for example:
• Remove properties and methods:
delete dog.name;
• Add additional properties and methods:
dog.say = function () {
return “Woof!”;
};
dog.fleas = true;
Starting with an empty object is optional. Literal Objects allow you to add the necessary functionality at the creation stage, as shown in the following example.
var dog = {
name: “Benji”,
getName: function () {
return this.name;
}
};
JavaScript doesn`t actually have empty objects. Even the simplest object {} already has properties and methods inherited from Object.prototype. By "empty" we mean an object that does not have other properties than those inherited.