Pardon the mess, Play My Code is in beta!


sign up - lost password


Arrays allow you to efficiently map an integer index to an object. Arrays are an object in their own right, with methods, and you can see the Array class for more information.

They are defined using the square brackets, and can contain initial values on creation.

emptyArray = []
nums = [ 3, 9, 2, 4 ]
names = [ 'John', 'Alan', 'Brian', 'Sam' ]

Setting Values

Indexes are positive whole numbers, and are the key for each set value. They store a value from every index from 0 (inclusive) to its size (exclusive). When setting a value outside of an arrays size it will automatically pad itself to fill the empty elements with 'null'.

names = []

names[0] = 'John'
names[2] = 'Alan'

// names[3] is automatically set to null
names[4] = 'Sam'

Retrieving Values

Values are retrieved using an index that returns the value stored there in the Array. If the index is out of bounds then 'null' is returned.

names = [ 'John', 'Alan', 'Brian', 'Sam' ]

name = names[ 0 ] // sets name to 'John'
name = names[ 2 ] // sets name to 'Brian'
name = names[ 9 ] // sets name to null

You can use negative indexes for retrieving values. These work back from the end of the array. So -1 refers to the last element, -2 to the second from last and so on.

name = names[ -1 ] // sets name to 'Sam'
name = names[ -2 ] // sets name to 'Brian'
name = names[ -9 ] // sets name to null

Like all other objects Arrays also contain methods, which you can find listed under the Array class.

2D Arrays

Multi-dimensional arrays can defined by just placing an array within an array. For example:

grid = [
        [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ],

The above defines a 2-dimensional grid of numbers; or an array of arrays. You can then access them like you would access a standard array.

number = grid[1][0] // returns 4

The first index pulls out the element stored at 1, which is the row '[ 4, 5, 6 ]'. The second index then returns the first item stored at 0, the value 4.

See Also