Web Programming

What's the difference between an indexed array and an associative array?

Arrays are objects. They can store multiple values in a single variable. An array can be:

					var scores = [89, 92, 97, 94];

					var states = [WI:"Wisconsin", MN:"Minnesota", IL:"Illinois"];


				
The first array called 'scores', has four numbers in it. The second array is called states. If you wanted to find '97' in scores, how would you find it? You could just count over 1, 2, 3, and say it was the third element in the array. But you would be wrong. Arrays in JavaScript don't start counting at 1, they start at 0. The first element in the array is '89' and it is in the 0th position, '92' is in the first, '97' is second, and so on. You could get the values like this: scores[0] = '89'; scores[1] = '92'; scores[2] = '97'; scores[3] = '94'; The values of state can be accessed using key-value pairs. You use a 'key' to get a 'value'. states['WI'] = "Wisconsin"; states['MN'] = "Minnesota"; states['IL'] = "Illinois"; A different way of looking at arrays is to see them as boxes with labels. An indexed array has boxes with numbers starting at 0. An associative array has boxes labeled with a key name. Looping through an array, the index or the key points to a value inside of it.