Arrays
Prev Chapter 2. JavaScript Basics Next

Arrays

Arrays are zero-indexed lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.

Example 2.25. A simple array

var myArray = [ 'hello', 'world' ];

Example 2.26. Accessing array items by index

var myArray = [ 'hello', 'world', 'foo', 'bar' ];
console.log(myArray[3]);   // logs 'bar'

Example 2.27. Testing the size of an array

var myArray = [ 'hello', 'world' ];
console.log(myArray.length);   // logs 2

Example 2.28. Changing the value of an array item

var myArray = [ 'hello', 'world' ];
myArray[1] = 'changed';

While it's possible to change the value of an array item as shown in Example 2.28, “Changing the value of an array item”, it's generally not advised.

Example 2.29. Adding elements to an array

var myArray = [ 'hello', 'world' ];
myArray.push('new');

Example 2.30. Working with arrays

var myArray = [ 'h', 'e', 'l', 'l', 'o' ];
var myString = myArray.join('');   // 'hello'
var mySplit = myString.split('');  // [ 'h', 'e', 'l', 'l', 'o' ]


Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
Reserved Words Home Objects