Data Structures

Videos

Examples from Videos

Notes

Data structures are basically fancy variables in Javascript that store data. A normal variable (x) stores a single value (x=7). A data structure can store a list of values or other more complex collections of values.

Arrays are essentially lists. You can create an array like this:

var states = [ "DC","Virginia","Maryland","Delaware"  ];

Items in arrays have numbers, and we start counting at 0. The first element in an array is number 0. In the states example, "DC" would be element 0. We call this number the index. You can use the index to get the value stored at this number. For example:
x = states[0];
Would store "DC" as the value of x. You can also use the index to put values in an array:
states[4] = "West Virginia";
You can add elements to an array with the command "push", which adds them with no need to keep track of the index:
states.push("New Jersey");
There are commands you can use on an array. For example, you can sort the values using the sort command:
states.sort();
Objects are another data structure, where you create a set of attributes of an entity. You create a variable and using this syntax, you add attributes with corresponding values:

var student = {
	firstName: "Jen",
	lastName: "Golbeck",
	hw1Score: 10,
	hw2Score: 9,
	hwAvg: function() {return (this.hw1Score + this.hw2Score)/2}
}

Note that you can also have functions in an object, as shown with hwAvg.

To get an attribute, you use the variable name (student in this case) followed by a dog and then the attribute

x = student.firstName
The code above would put "Jen" as the value of x.

You can also use functions in the same way:

y = student.hwAvg();
That would store the average value in the variable y.