• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / JavaScript Arrays / JavaScript Array Basics

JavaScript Array Basics

5 May 2008 / 4 Comments

Like most languages, JavaScript lets you create arrays to store bunches of values in. An array is simply a sequence, or list, of values. A value in a JavaScript array can be anything from a number or string, through to a function or an object; JavaScript arrays can store pretty much any type of data. A single value in a JavaScript array is called an element.

With JavaScript arrays, you can:

  • Store any number of values, including no values at all (known as an empty array)
  • Access any or all the elements of an array through a single variable name
  • Read and write elements of an array
  • Loop through all the elements of an array
  • Join two or more arrays together to make one longer array
  • Convert an array to one long string
  • Add or remove elements from the beginning, end, or middle of an array
  • Reverse the order of the elements in an array
  • Sort the elements of an array in any order you like
  • Nest arrays within other arrays

JavaScript stores arrays as Array objects, so most of the things you can do with arrays revolve around the properties and methods of the Array class.

In this introductory article, you look at creating arrays, accessing the contents of arrays, the concept of array lengths, and looping through arrays.

Actually there is an upper limit on the number of elements in an array, but since that limit is 4,294,967,295, you probably won’t come across it very often!

Creating a JavaScript array

There are many ways to create a JavaScript array. For example, you can use an array literal, as follows:


// Create an empty array
var emptyArray = [ ];

// Create an array of fruit
var fruits = [ "apple", "pear", "orange", "banana" ];
A literal is a fixed value that you type directly into your code.

You can also create a new Array object:


// Create an empty array
var emptyArray = new Array ( );

// Create an empty array that's 15 elements long
var emptyElementsArray = new Array ( 15 );

// Create an array of 1 element
var myName = new Array ( "Matt" );

// Create an array of fruit
var fruits = new Array ( "apple", "pear", "orange", "banana" );
The array you create depends on the number and type of values you pass to the Array constructor. Supplying no values produces an empty array of zero length. Passing a single numeric value creates an empty array of that length. Passing more than one numeric value, or one or more non-numeric values, creates an array containing those value(s) as individual elements.

You’re not limited to passing literal values to the Array constructor. For example, you can create an array containing the values of some variables:


var favouriteFruit = "banana";
var favouriteColour = "red";
var favouriteNumber = 8;

var favourites = new Array ( favouriteFruit, favouriteColour, favouriteNumber );

The above code produces the following array:


[ "banana", "red", 8 ]

You can even create arrays of functions and objects. For example, the following (rather pointless) array contains the DOM window object, the DOM document object, and the String.unescape() function:


var randomStuff = new Array ( window, document, unescape );
If you create an array by passing in numeric or string variables, the array contains copies of those variable’s values. For example, if you changed favouriteColour to “blue” after creating the favourites array in the above example, the value inside the array would still be “red”.

However, if you create an array of functions or objects, the array contains references to those functions or objects. For example, if you change an object in an array by referencing it elsewhere, the object inside the array is also changed (because it’s actually the same object).

Accessing the contents of an array

Each element in an array is given an index, which is an integer value between 0 and one less than the length of the array. The first element has an index of 0, the second element has an index of 1, and so on.

To access an element, use the syntax:


arrayName[index]

For example, using our favourites array that we created above:


alert ( favourites[0] );
alert ( favourites[2] );

…produces 2 alert boxes with the values banana and 8 respectively.

As well as reading array elements, you can also write to array elements in a similar fashion. For example:


favourites[0] = "apple";

…changes the first element of the favourites array from “banana” to “apple”.

Understanding array lengths

To retrieve the length of an array, use its length property, as follows:


var fruits = new Array ( "apple", "pear", "orange", "banana" );
alert ( fruits.length ); // Displays "4"

The length of an array isn’t necessarily the same as the number of elements in an array. For example, the following array has a length of 15, but it only contains a single element:


var myArray = new Array ( 15 );
myArray[0] = "myValue";

You can also set an array’s length at any time:


myArray.length = 50;
  • If you set an array’s length to be greater than its current length, no new elements are created; the array merely ends up with a longer length property.
  • If you set an array’s length to be less than its existing length, you shorten the array’s length property. In addition, any elements with indices that fall outside the new array length are discarded.

You can also increase the length of an array by adding a new element with an index greater than or equal to the array’s current length. The example below changes myArray‘s length from 15 to 100:


myArray[99] = "anotherValue";

If you set an array to be a certain length, all values within the array that have not been explicitly defined have the value undefined. So in the above example, myArray[0] contains “myValue”, and myArray[1] – myArray[99] all contain the value undefined.

Looping through arrays

One of the most useful things about a JavaScript array is that you can use a loop to move through each element of the array in turn. Consider this non-looping example, which displays each of the six fruits in the fruits array in turn:


var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );

alert ( fruits[0] ); // Displays "apple"
alert ( fruits[1] ); // Displays "pear"
alert ( fruits[2] ); // Displays "orange"
alert ( fruits[3] ); // Displays "banana"
alert ( fruits[4] ); // Displays "peach"
alert ( fruits[5] ); // Displays "strawberry"

As you can imagine, this starts to become unwieldy when you have a lot of elements in your array.

Here’s how to do the same thing with a for loop:


var fruits = new Array ( "apple", "pear", "orange", "banana", "peach", "strawberry" );

for ( i=0; i < fruits.length; i++ )
{
  alert ( fruits[i] );
}

Not only is the loop version more compact, but you can use it to handle any number of array elements without needing to change the code.

Further reading

Now that you know the basics of JavaScript arrays, take a look at Manipulating JavaScript arrays, which explains how to extract portions of an array; how to join arrays together; how to convert an array to a string; and how to add and remove elements from an array.

The Mozilla Developer Center has a good reference covering the Array class. W3Schools also summarizes Array‘s methods and properties and provides some handy examples that you can try out.

Filed Under: JavaScript Arrays Tagged With: array object, class, constructor, for loop, index, introduction, javascript arrays, literal, syntax

Reader Interactions

Comments

  1. sebarmeli says

    7 December 2010 at 3:20 am

    This is an optimization of the loop:

    for(var i=0, len=myArray.length; i < len; i++){}

    as the length is “cached” and not recalculated every time.

    If you want to know more details about this topic, read my post http://bit.ly/arrayjs

    Reply
  2. puffafish says

    11 February 2013 at 5:17 am

    In the Array length section it states:

    “myArray[99] = “anotherValue”;

    If you set an array to be a certain length, all values within the array that have not been explicitly defined have the value undefined. So in the above example, myArray[0] contains “myValue”, and myArray[1] – myArray[99] all contain the value undefined.”

    Surely myArray[99] should be “anotherValue”, not undefined, or am i mistaken?

    Regards,
    Clive

    Reply
  3. iqramul123 says

    22 November 2016 at 6:31 am

    please help me with this

    an array of products can be set up as below for use on an ecommerce web site.
    var products = [“Printer”,”Tablet”,”Router”];
    Set up an array to include the items shown above, plus a few extras of your choice.
    Write a script that:
    outputs the items in alphabetical order
    counts the number of items in the array

    Mod Edit;
    Replies are done in the forum so every body can benefit.

    [Edited by chrishirst on 22-Nov-16 15:25]

    Reply
  4. chrishirst says

    22 November 2016 at 3:28 pm

    Count items;
    http://www.w3schools.com/jsref/jsref_length_array.asp

    sort array;
    http://www.w3schools.com/jsref/jsref_sort.asp

    All array methods and properties;
    http://www.w3schools.com/jsref/jsref_obj_array.asp

    Reply

Leave a Reply Cancel reply

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

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits