JavaScript

JavaScript: Part 3

Objects

The simple type of JavaScripts are numbers, strings, booleans (true and false), null and undefined. All others values are objects. Numbers, strings, and booleans are objects-like in they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects and of course, objects are objects.

An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string. A property value can be any JavaScript value except for undefined.

Objects in JavaScript are class-free.

Objects are useful for collecting and organizing data.

JavaScript includes a prototype linkage feature that allows you one objects to inherit the properties of another. When used well, this can reduce object initialization time and memory consumption.

Object Literals

Objects literals provide a very convenient notation for creating new object values. An object literal is a pair of curly braces surrounding zero or more name/value pairs. An object literal can appear anywhere an expression can appear.

var empty_object = {};
var stooge = {
"first-name": "Joy",
"last-name": "Jack"
}

A property’s name can be any sting, including the empty string. The quotes around a property’s name in an objects literal are optional if the name would be a legal JavaScript name and not a reserved word. Hence quotes are required around “first-name” but are optional around first_name.

A property’s value can be obtained from any expression, including another object literal. Objects can nest:

var jo = {
  height: 170,
  age: 26,
  location: "India"
  qualification: {
    HSC: "BOM"
    SSC: "DEL"
    BBA: "PNQ"
  },
  skills: {
    React: "Yes"
    JAVA: "NO"
 }
};

Retrieval

Values can be retrieved from an object by wrapping a string expression in a [] suffix. If the string expression is a constant, and if it is a legal JavaScript name and not a reserved word, then the .notation can be used instead. The .notation is preferred because it is more compact and it reads better.

stooge ["first-name"] // "Jo"
jo.qualification.BBA  // "PNQ"

An undefined values is produced if an attempt is made to retrieve a nonexistent member:

stooge["middle-name"]       // undefined
jo.status                  // undefined
stooge["FIRST-NAME"]      // undefined

The || operator can be used to fill in default values:

var middle = stooge["middle-name"] || "(none)";
var status = jo.status || "unknown";

Attempting to retrieve value from undefined will throw a TypeError exception. This can be guarded against with the && operator.

jo.hobbies                        // undefined
jo.hobbies.indoor                //  throw "TypeError"
jo.hobbies && jo.hobbies.indoor // undefined

Update

A value in an object can be updated by the assignment. If the property name already exists in the object, the name will be replaced.

stooge["first-name"] = "Joy";

IF the object already does not have that property name, the object is agumented:

stooge["middle-name"] = "Lee";
stooge.nickname = "Sim";
jo.hobbies = {
  indoor = {
    cards: "UNO",
    Board: "Jumanji"
  },
  outdoor = {
    Trek = 100,
    Cycling = 200
};
jo.status = "Single";

Reference

Objects are passed around by reference. They are never copied:

var x = stooge;
x.nickname = "Sim";
var nick = stooge.nickname;

// nick is "Sim" because x and stooge are reference to the same object.
var a = {}, b = {}, c = {};

// a b c all are referred to a different empty object

a = b = c = {};
// a b c all are referred to the same empty object

Prototype

Every object is linked to a prototype object from which it can inherit properties. All objects created from object literal are linked to object.prototype, an object that comes standard with JavaScript.

when you make a new object, you can select the object that should be in prototype.

We will add a beget method to the object function. The beget method creates a new object that uses an old object as its prototype.

if (typeOf Object.beget ! == 'function') {
 object.beget = function (0) {
  var X = function() {};
  X.prototype = 0
 return new X();
 };
}
var another_stooge = object.beget(stooge);

The prototype has no effect on updating. When we make changes to an object, the object’s prototype is not touched.

another_stooge[ 'first-name'] = 'Jack';
another_stooge[ 'middle-name'] = 'Jill';
another_stooge.nickname = "Joe";

The prototype link is only used in retrieval. If we try to retrieve a property value form an object, and if object lacks the property name, than JavaScript attempts to retrieve the property.

The prototype relationship is a dynamic. If we add a new property to a prototype, that property will immediately be visible in all of the objects that are based on that prototype:

stooge.profession = 'Developer';
another_stooge.profession =     // 'Developer'

Reflection

It is easy to inspect an object to determine what properties it has by attempting to retrieve the properties an examining the value obtained. The typeof operator can be very helpful in determining the type of a property.

typeof qualification.BBA // 'string'
typeof hobbies.Outdoor  // 'number'
typeof skill.React     // 'object'

Some care must be taken because any property on prototype chain can produce a value

There are two ways of dealing with these properties. First to have you program look for and reject function values. The other approach is to use the hasOwnProperty method. Which returns true if the object has a particular property.

jo.hasOwnProperty('number')     // true
jo.hasOwnProperty('function')  // false

Enumeration

The for in statement can loop over all of the property name in an object. The enumeration will include all of the properties, including function and prototype. Prototypes that you are not interested in. So it is necessary to filter out the values you don’t want. The most common filters are hasOwnProperty method and using typeof to exclude functions.

var name
for (name in another_stooge) {
  if (typeof another_stooge[name] ! == 'function') {
    document.writeIn(name + " " + another_stooge[name]);
  }
}

There is no guarantee on the oder of the name. So be prepared for the names to appear in any order.

If you want the properties to reflect in order. It is best to avoid the for in statement entirely and instead make an array containing the names of the properties in the correct order.

var i;
var properties = [
  'first-name',
  'middle-name',
  'last-name',
  'profession'
];
for (i = 0; i < properties.lenght; i += 1) {
  document.writeIn(properties[i] + " ; " + another_stooge[properties[i]]);
  }
}

By using for instead of for in, we were able to get the properties we wanted. We got them in correct order

Delete

The delete operator can be used to remove a property from an object. It will not touch any other object in the prototype linkage.

delete another_stooge.nickname

Global Abatement

JavaScript makes it easy to define global variables that can hold all of the assets of your application. Unfortunately global variables weaken the resiliency of programs and should be avoided.

One way to minimise the use of global variable is to create a single global variable for your application:

var MYAPP = {};

This variable is now container for you application:

MYAPP.stooge = {
  "first-name" = "Jo",
  "last-name": "Jack"
};
MYAPP.jo = {
  height: 170,
  age: 26,
  location: "India"
 qualification: {
    HSC: "BOM"
    SSC: "DEL"
    BBA: "PNQ"
  },
 skills: {
    React: "Yes"
    JAVA: "NO"
 }
};

By reducing your global footprint to a single name , You reduce the chance of bad interaction with other applications. Your program becomes easier to read.

Thankyou!

Leave a Comment

Your email address will not be published. Required fields are marked *

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

%d bloggers like this: