Error Messages Working with Arrays: undefined

By: Dusty Arlia
Published on September 20, 2012
Last Updated on Wednesday, July 08, 2015 at 10:13 PM
Total Updates: 7

Whenever you try to access an item in an array using its index number, be sure that you use the correct index number. If you were to use an index number outside the range of actual index numbers in use, then you will receive the undefined error message. This suggests that there is no location in memory where you're telling the JavaScript interpreter to look. Look at this example:

var newsChannels = ['CNN',
                    'FOX',
                    'MSNBC',
                    'The Daily Show'];
document.write(newsChannels[4]);

Here the last item in the newsChannels array is the The Daily Show string with an index number of 3. The last index number is always the number of items in the array minus one, because index numbers start with the number 0. document.write(newsChannels[4]); tries to print a value in the fifth position of the newsChannels array to the screen, but there is no value there. You will see the error message undefined printed to the screen.

Comments:

Ad: