JavaScript arrays, functions and objects

In javascript arrays and functions are very much alike. They are more like brother and sister than like neighbors. Arrays can hold values, which can include objects and functions. Functions can also hold these in their properties, but in addition can act as Class templates to create new objects. They are both objects by the way.

Let’s look at some data viewed in various incarnations, to illustrate the concept:

An array

var fruit = new Array();
fruit['first']='apple';
fruit['second']='banana';
fruit['third']='cherry';

Note that this uses strings as index values, creating a so-called Hash or Dictionary. It is different from a traditional array, which uses numbers as index values, as in:

var fruit = new Array();
fruit.push('apple');
fruit.push('banana');
fruit.push('cherry');

or

fruit = ['apple', 'banana', 'cherry'];

A function

var fruit = function()
{
  this.first = 'apple';
  this.second = 'banana';
  this.third = 'cherry';
}

It’s important to note that there is a major difference between a function and an object. When a function is created it can act like a constructor (class template), creating new objects with the ‘new’ keyword. Objects cannot do this themselves.

An object

var fruit = new Object();
fruit.first = 'apple';
fruit.second = 'banana';
fruit.third = 'cherry';

this can be rephrased as

fruit = {first:'apple', second:'banana'; third:'cherry'};

Note the weird ending of the line with “;};” which is correct in this case.

Advertisements

One thought on “JavaScript arrays, functions and objects

  1. the last example :
    # fruit = {first:’apple’, second:’banana’; third:’cherry’;};

    is wrong! the right thing to do is:

    var fruit = {first:’apple’, second:’banana’, third:’cherry’};

    Thanks for the article 🙂

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