Stein Programming

Javascript Arrays

Arrays in javascript are like containers or shelves that store a list of values. These values will generally be related to one another. The array itself allows you to continue to add to it and whenever it is accessed in code adapts any new changes to the code accessing it. If there is code that asks to show an array of current residents for a building and a new resident is added to the array, that new resident will show up without having to change the callout for the array.


You would want to use an array when you are working with a list or a set of values that are related. This is especially important when you are unsure of how many items or values will be present because with arrays you do not need to specify the amount. The array will adapt to and allow for adding however many items you wish to add or delete.


The code example below is how you would implement an array in code. This example is a list of dogs that gives the name, breed, gender, age, and vaccination status. First, you start out by declaring the variable itself as var dogs. This is the name for the array and what you will be accessing when calling out the array in code. Following the declaration is a pair of brackets which contain the three list items in the array. This array could be as simple as just containing the strings Brutus, Fido, and Daisy with commas separating each which would create a simple list of dog names. This example however has three items held within curly braces that go into more detail. By doing it this way you are able to give extra details associated with each item at the time of implementation rather than adding them later.

var dogs = [
		{name: "Brutus", breed:"Boxer", gender: "male", age:7, vaccinated:true},
		{name: "Fido", breed:"Pit Bull", gender: "female", age:3, vaccinated:false},
		{name: "Daisy", breed:"Labrador", gender: "female", age:2, vaccinated:true}
];