JavaScript Rants Part One – Simple Objects and Properties

Posted: February 2, 2013 in JavaScript

For so long I have been wanting to write some posts about JavaScripts! Today I finally managed to find some time to write the first one of them! This will be the first post in a series of posts about JavaScripts. Today my writing topic will be simple objects and properties.

Objects

In JavaScript, objects are just collection or propertieswhere a property is just a key-value pair. A simple JavaScript object may look like this –

var obj = {
    key: 'my value'
};

That’s it. It’s as simple as that. Any kinds of objects, no matter how complex it is, can be summarized to just a key-value store.

Creating objects and properties

There are basically three common ways to create objects in JavaScript. Each of them is illustrated in the following example –

/* 1. The object literal syntax. It's the most simplest
 * form of object creation.
 */
var obj = {};

/* 2. With the Object.create method, specifying the prototype
 * for the object. ECMAScript 5+ only.
 */
var anotherObj = Object.create(null);

/* 3. With Object constructor
 */
var lastObj = new Object();

All of the above three methods create an empty object which has no property. They all appear to be doing the same, creating an empty object with no properties, but this is not the case.

Each of the above three methods have their own advantages/disadvantages, and the second method creates an object which has no prototype (You: wait, what now? Me: keep patience, this is only part one).

Once the object has been created, there are four ways we can create properties for the object –

/* 1. The dot notation
 */
obj.firstProperty = 'this is a property';    // set property
var value = obj.firstProperty;    // get property
console.log(value);

/* 2. Square bracket notation
 */
anotherObj['key'] = 24;    // set property
var result = anotherObj['key'] + 6;    // get property
console.log(result);

/* 3. With Object.defineProperty. ECMAScript 5+ only.
 */
// Set property
Object.defineProperty(lastObj, 'key', {
    value: 'this is key value',
    writable: true,
    enumerable: true,
    configurable: true
});

// get property - use any of the method described in 1 or 2
console.log(lastObj.key);

/* 4. With Object.defineProperties. ECMAScript 5+ only.
 */
// Set property
Object.defineProperties(obj, {
    'secondKey': {
        value: 'I am second',
        writable: true
    },
    'thirdKey': {
        value: 'I am third',
        writable: false
    }
});

// get property - use any of the method described in 1 or 2
console.log(obj.thirdKey);

Method 1 and 2 are almost same, except that if a property name is not a valid identifier (you know, names starting with letters, or names not containing valid characters etc.), then method 1 will generate an error, while method 2 won’t. You can also use a variable inside a square bracket, whose value will first be substituted there, and then be converted to string, and then be used as a key!

Method 3 provides much more flexibility than method 1 and 2 over the property creation.

How?

Besides creating properties and setting their values, these methods also allow us to input property configuration! Each JavaScript property has a property descriptor consisting some attributes/properties which describes their characteristics –

  1. writable: Can we change the value of this property after it has been created using the assignment operator? This attribute answers this question. If it’s set to true, value of a property can be changed once it’s created. If it’s set to false, we won’t be able to change the value once the property has been created. This gives rise to immutable properties in JavaScript.
  2. enumerable: Can we enumerate/traverse this property using the in (You: again, wait. What’s this?! Me: again I am saying, this in only first part, dam’it) operator (or, in some other similar way)? This attribute answers this question. If set to true, we will be able to enumerate this property using the in operator, otherwise we can’t.
  3. configurable: Can we delete this property or change it’s property descriptor after it’s been created? This attribute answers this question. If set to true, we can delete this property from the object using the delete operator (see below) or change it’s descriptor (use defineProperty again with different configuration value). Otherwise, we can’t.

Note: Even after setting configurable to false, you can still change the writable configuration from true to false. This is the only exception. The reason behind this is described here pretty nicely.

You can define a variable (beware of polluting the global namespace!!) and a function for your convenience to create object properties in this way –

var config = {
    writable: true,
    enumerable: true,
    configurable: true
};

function defineProperty(object, key, value) {
    config.value = value;
    Object.defineProperty(object, key, config);
}

var myObject = {};
defineProperty(myObject, 'first', 'hello');

config.writable = false;
defineProperty(myObject, 'second', ' world');

Method 4 is just a variation of 3 which enables us to define more than one properties at the same time.

Play with these as long as you want. You may use Firebug as your playground.

Deleting properties

You can delete an object property using the delete operator –

var myObject = {};
myObject.key = 'value';

console.log(myObject.key);    // will print "value" on console

delete myObject.key;

console.log(myObject.key);    // will print "undefined"

That’s it for today. I’ll try to write the second post as soon as I can. Any comments – suggestions, corrections, modifications – are welcome!

Acknowledgements

  1. Addy Osmani: Learning JavaScript Design Patterns
  2. Yehuda Katz: Understanding Prototypes in JavaScript
  3. Juriy Zaytsev: ECMAScript 5 compatibility table
Advertisements
Comments
  1. name says:

    ); in method 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s