Objects and Arrays

JavaScript has powerful and flexible object-oriented capabilities with strong support for objects, arrays, hashes and classes. Objects are the foundation of the object-oriented capabilities of JavaScript. They may be dynamically created and are automatically garbage collected. Unlike strongly typed languages such as C++ and Java, object definitions and classes may also be easily created at run-time.

Objects

An object is a collection of zero or more named properties. They are dynamic in that they can add properties at run-time and do not have any fixed contents.

Objects are created via the new operator and properties are accessed by using dot notation.

var o = new Object
o.color = "red"

Property Names

To use dot notation, property values must be valid JavaScript identifier names. This means beginning with an alphabetic, "_", or "$" character and having no spaces. If you need to have properties that are not valid identifiers, then you can use the array subscripting method to create or access properties.

var o = new Object
o["My Favorite Color"] = "red"
o.color = "blue"

You can mix and match dot notation and array index notation to access properties. By using the array index notation, the object effectively behaves as an associative hash.

Property Values

Property values may be any object or JavaScript type. They may also be functions, in which case, they are referred to as object methods.

o.print = function () {
    print("Color is " + this.color)
}

Creating Objects

Objects are created via the new operator which returns a reference to the object. Objects are not created in a local or global variable store. Rather, they are created in the memory heap. When the result of the new operator is assigned to a variable, a reference to the object is stored in the variable. Consequently, there may exist multiple references to an object at any time. When there are no remaining references, the object is not accessible and is eligible to be reclaimed by the garbage collector. For example:

var o = new Object
var o2 = o;

After the assignment to o2, there are two references to the object. You can explicitly remove a reference to an object by assigning another value or null to a variable. Continuing the example above, if we assign null to the variable "o", then the object created will have only one reference. Assigning null to o2 will remove the final reference and the object will be garbage collected.

When objects are passed to functions, they are passed by reference. The object itself is not copied.

Object Literals

Objects can be created and initialized by using an object literal syntax. This consists of a comma separated set of key,value pairs.

var user = {
    name: "Josh",
    age: 29,
    occupation: "Engineer",
}

You can also use an empty literal as a convenient short-hand to create an empty object.

var empty = {}

Object Methods

When functions are stored as object property values, they become object methods. When an object method is invoked, the this pseudo-property is set to the object reference when code inside the function is executing.

Standard Methods

The Object type defines the toString method which converts the object representation into a string. Because all data types, objects and classes inherit from Object, values always have a toString method defined.

The default toString method returns "[object Object]". You may override the toString method by assigning your own function to the toString property in your object constructor.

Classes

Classes may be created by using a combination of Objects, constructor functions and prototype objects. This technique of creating classes and objects is called Prototype Inheritance. For information about creating classes and Prototype Inheritance, see the Classes and Interfaces document.

Arrays

A JavaScript array is an ordered collection of values. Arrays can store arbitrary values with numerical indices that begin at zero. Like objects, new arrays are created using the new operator. Values are accessed using the array bracket notation.

var colors = new Array
colors[1] = "red"
colors[0] = "blue"

Array Constructor

There are several ways to use the Array constructor. You can create an empty array, an empty array of a specific size, and an initialized array.

var empty = new Array                               // Empty array
var ten = new Array(10)                             // Empty with 10 slots
var products = new Array("milk", "eggs", "bread")   // three elements

When an array is created, the length property is set to the current length of the array. When an array is created with a single size parameter, it's length will be set to the requested size and all the elements in the array will be set to undefined.

Associative Arrays

But JavaScript arrays have hidden depth. They build upon the object class and also allow non-numerical properties.

colors["Favorite Color"] = "red"

When using alphabetical indices, the array operates as an associative array. When using numeric indices, it behaves more like a classical array. In both cases, arrays will grow on demand as new elements are stored in the array and may be garbage collected when the array is no longer referenced.

Ejscript compacts and optimizes the storage of Array elements and stores the elements with numerical indices separately from those with alphabetical indices.

Array Literals

Arrays can also be created and initialized by using an array literal syntax. This consists of a comma separated set of values.

var colors = [ "red", "white", "blue" ]
var emptyArray = []

Similarly to object literals, You can use an empty literal as a short-hand to create an empty array.

Multi-Dimensional Arrays

By storing arrays as elements of arrays, multi-dimensional arrays can be created. You can use the literal syntax to create these.

var grid = [[1,2,3], [10,20,30], [100,200,300]]

Accessing elements is done via repeated indexing.

var element = grid[2][2]
print(element)
/* Emits */
300

Iteration and Enumeration

There are two different approaches to walking array or object elements: Iteration and Enumeration. Iteration is where you step through the array indices or object property names. Enumeration is where you step through the the array element or object property values. If you need the actual values, but not the indices or property names, then enumeration is the preferred and faster approach.

Iteration

You can iterate step through array elements in two ways. The first way is to use a simple, traditional for loop.

for (i = 0; i < colors.length; i++) {
    print(colors[i])
}

The second way is to use a for .. in loop.

for (let i in colors) {
    print(colors[i])
}

Enumeration

To enumerate the elements of an array or object property values, use the for each statement.

for each (let color in colors) {
    print(color)
}

© Embedthis Software, 2003-2015. All rights reserved.