Today’s tutorial comes with a little surprise. Today, we’ll be talking about “associative arrays.” If you’ve programmed before, then you probably know what these are. If you don’t, then don’t worry. I’ll explain it in a bit.
Creating An Associative Array
Clear your script and add this bit of code.
var jack = new Array();
jack['age'] = 19;
jack['gender'] = 'male';
jack['height'] = 70;
You use the square bracket notation to give your key names and then a string inside for their name. Add this bit of code into your script.
document.write( jack['age'] );
You should get 19 outputted onto the document. This is what an associative array is! It’s an array with names for indexes instead of numbers. Now, here comes the surprise.
Associative Arrays don’t exist!
If you’ve programmed before and know what associative arrays are, then you may be confused because they seem like it. Well, let’s try something first. Update the line that outputs onto the document to this.
document.write( jack.length );
We all know what this does. It simply outputs the amount of elements inside of an array. If you refresh your page, then you get 0! It should be 3 because we have 3 elements in our array, but this is actually far from the truth.
Arrays are objects. I’ve stated this before, but when you try to create elements this way, you’re actually creating properties. Another way to access and/or create properties is using square bracket notation.So, technically, you’re not creating elements at all. Therefore, the length property will always return 0.