Arrays

Array Creation

An Array is just a collection of values. When creating an Array you can usually create it either with or without preset values. Some languages don’t require the size of an Array to be specified during declaration, but most do.

JavaScript

// To get the results below open your browsers developer tools, 
// hit F12 on the keyboard. Then select the console and you 
// will be able to type the code below

// Array syntax
var a = [];
undefined
a;
[] 

// New syntax 
var b = new Array();
undefined
b;
[]

// New syntax specifying size
var c = new Array(5);
undefined
c;
[undefined x 5]

Populating Arrays

A list of values would be useless if you couldn’t set what those values are. So, there are generally a couple ways to set the values within an Array. Most languages allow the configuration of an array to happen during creation. Also, values my be set individually after creation. As an important note, Arrays in every language that I am familiar with are zero based. Zero based means that the positions of an array start at 0 instead of 1; so, the first position is 0, the second position is 1 and so on.

JavaScript

// Assignment of values during creation
var d = [1,2,3,4,5];
undefined
d;
[1, 2, 3, 4, 5]

// Assignment by accessing the array index
var e = [];
undefined
e[0] = 1;
1
e;
[1]
e[1] = 2;
2
e;
[1, 2] 

// Non-contiguous values - JavaScript allows the addition of
// values without the need to fill values in-between
e[6] = 7;
7
e;
[1, 2, undefined x 4, 7]

Accessing Values

Arrays would be useless if you couldn’t get the values back out of them. In most languages the way you would access a value is by index. When accessing the value it is extremely important to remember that arrays are zero based. Forgetting that aspect of Arrays has led to more bugs in applications, probably, than any other singular mistake. This problem is known as an “off by one” error.

JavaScript

// Accessing an array values by index
f = [1, 2];
undefined
var g = f[1];
undefined
g;
2

We’re Done

That is all there is to Arrays for now. As Always, I hope you learned something from this, but if not please look at some of the other articles as they are more advanced and may lend you some insight in the world of software development.

Leave a Reply

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