Now things are getting interesting. This lesson is about arrays. We know how to set a variable equal to one value. What if we’ve got a bunch of values that go together? That’s where arrays come in.
Arrays are basically lists of different values, they can be a mix of strings, numbers, or boolean values, pretty much anything. The thing to remember is each value is associated with a number, but the first value isn’t one, we start with zero. So the array counts up or is indexed from zero to however many values you want to stick in it, there is no limit.
We use these numbers to put stuff into the array and pull stuff out. Let’s create an array like this:
Javascript uses square bracket to indicate an array. This array contains my codebabe stats, measurements of course, then my operating systems of choice, and favorite programming language.
You can see that it’s easy to mix integers and strings in an array. Array values get assigned numbers automatically. The thing to remember is that they start with zero. So my first measurement would be numbered zero.
But let’s say I wanted my measurements to be their own array. No problem. We can just wrap those numbers in square brackets, now we have an array within an array. An inception array.
If we log the array, go back and refresh the browser, we’ll see the values printed out, plus the values of the new array value within babe stats.
What if we wanted to grab something out of the measurements array now? We could do that by just adding another set of square brackets. Say you want to grab my waist, we just do console log babe stats zero and then one. Zero because the array values start with zero and one for the second value of the measurements array!
What if we wanted to add something to the array? To do this we need to use the javascript method "push", like this:
That would add another value to my babe stats. A method is another word for function in Object oriented programming lingo. You’ll have to watch another codebabes course on OBJECT oriented programming for that explanation. For now just take our word for it. If we log the array again we'll see the value that was pushed appended to the end.
Ok good work, you guys will get the hang of it. Next we’ll talk about loops, which go together with arrays like tantric sex and oil!
Questions or Comments?