17 Arrays and Objects
Flexible Arrays
Like most programming languages, JavaScript supports an indexed data type (called an array) for storing ordered lists of values. JavaScript arrays are flexible (they can grow and shrink after they are created) and dynamic (they can contain a mixture of value types).
Do it Yourself
You ought to be able leverage your understanding of indexed data types (arrays or lists) from your first programming course along with your growing understanding of JavaScript to describe the effect of this JavaScript code:
let a = [3, 4, 5]; for(let i = 0; i < a.length; i++) a[i] = a[i] * 2;
Take a minute to think about what this code does, then type or paste it into a browser console window to run it, and then type a and press enter to examine the contents of the array. Did you get it right?
Connections
Python does not have an array type, but it has a data structure called a list which is similar in many ways.
Java and C have a true array type in which you must declare a type and a size for the array. A true array can only contain elements of one type and cannot change its size after it is created.
If you do not have experience with Java, C, or a similar language, you may need to take a second to learn about the C-style for loop. If so, see JS Loop For on W3Schools.
The following pieces of code creates an empty array.
let a = [];
You can also create an array with some initial contents, like this:
let a = [43, "hello", -2.5, true];
The expressions in square brackets above are called array literals. In JavaScript, you can use array literals anywhere you could use an array.
Notice that this array contains values of three different types (Number, String, and Boolean). Dynamic typing also allows you to mix values of different types in a single array. In fact, you can even have arrays stored within other arrays.
Do it Yourself
Type or paste this line into a browser console and hit enter.
var a = [6, [5, 3, -2], "JavaScript"];
How many items does the array a have in it? Type a.length to find out.
What does each item contain? Type a[0], a[1], and so on to find out. What if you type a[1][1] or a[2][5]? What do you expect to be the result? Try it to see if you were right.
Now try this:
for(let e of a) { console.log(e); }
The above is a for-each loop. It declares a variable called e and then assigns each element from a to the variable e and runs the code block.
You never have to declare the size of an array in advance because you can arbitrarily extend its length after you create it.
Do it Yourself
Type or paste the following into a browser console.
let a = []; a[0] = -23; a[1] = 45; a.push(100); a.push(-1);
Now type a and hit enter to see the contents of the array. This shows two different ways of extending the length of an initially empty array. Type a.length to see the new length, and use a for-each loop to print out the contents (see DIY box above).
It is also possible to create an array with “holes” in it.
Do it Yourself
Complete the previous DIY box, and then in the same console window, type the following:
a[9] = 0;
You just created an array with 5 “holes in” it from indices 4 to 8. How long is the array now? Type a.length to find out, then type a and hit enter to find out what the contents of the array looks like.
The “empty” elements in the array will report the special value undefined if you try to access them.
So if you are ever not sure whether an array index has been given a value, you can test it in an if statement. Try this:
if (a[3] === undefined) alert("index 3 is undefined"); else alert("index 3 is in use");
Now use a for loop or a for-each loop to print the contents. What do you get?
Gotcha: Index Errors
You will never get an index error from JavaScript. Even if the array is empty, you can still access any index of that array, and JavaScript will report the special value undefined!
Arrays are also objects. They contain variables and functions that you can access with the dot operator. For example, a.length reports the length of the array, a.push appends to an array, a.sort will sort the array elements, a.findIndex will search the array, and so on.
Do it Yourself
Define an array named a in the console. Then type a. (with the dot) and explore the list of methods that pops up. If you select one and type an open bracket “(” you will see the parameters it requires. Explore and see what you can find.
W3Schools has a nice reference for JS Array Methods.
Objects
An object is an encapsulated package of variables (sometimes called attributes, fields, or properties) and functions (referred to as methods) that can be stored together under a single variable name. In your experience with other programming languages, you have probably used objects before, and you may even have created your own objects by defining a class with a constructor or initializer method.
For example, in JavaScript, Strings and Arrays are objects. Every String and Array object has a field named length and a number of methods that can be called to process them.
Do it Yourself
Try this in a console window or a script element of a web page. Predict the result of each line before you run it.
let s = "JavaScript is Cool."; alert(s.length); alert(s.indexOf("Cool"));
The second line in the code above accesses the length field associated with the object s. The third line calls the indexOf method of s with an argument of 0.
Objects as Associative Arrays
One thing that is different about JavaScript is that you can use either dot notation or square bracket notation to access an object’s properties and methods. For example, instead of s.length and s.indexOf, you can write s[“length”] and s[“indexOf”] as shown in the DIY box below.
This square bracket object notation looks and behaves exactly like a data structure called an associative array (or sometimes a map or a dictionary). Indeed, there is no meaningful difference between an object and an associative array in JavaScript, so both styles of referencing are included for the convenience of the programmer.
Do it Yourself
Try this in a console window or a script element of a web page.
let s = "JavaScript is Cool."; alert(s["length"]); alert(s["indexOf"]("Cool"));
This square bracket style of accessing an object’s fields and methods might seem strange, but it has its uses. For example, try the following (after the lines above). Make sure you type something legal like “length” when prompted.
let fieldName = prompt("type a field name"); alert( s[fieldName] );
Creating Objects
Objects can be created in a number of ways in JavaScript, and we will take a more in-depth look in a future chapter. But for now, one quick and easy way to create an object is to list a set of fields and values inside braces { }.
Do it Yourself
Use the code below in a JavaScript console to create an object with three fields, name, age, and access.
let person = {name: "Sam", age: 55, access: true};
Try using both dot and associative array notation to access and change the three fields of the person object.
Objects are also highly flexible in JavaScript. You can create a new field for an object simply by assigning a value to it.
Do it Yourself
You use either of the lines below to add a children field to the person object from the last DIY box, and assigns an array to it.
person.children = ["Max", "Rosa"]; person["children"] = ["Max", "Rosa"];
Use both styles to write an expression that will access the first name in the children array.
Connections
Python contains a dict datatype that behaves in many ways like a JavaScript object. In fact most of the code above would work exactly as written in Python. The main difference is that you cannot use dot notation to access the fields of a dict.
Java contains a HashMap class in its Collections hierarchy that implements an associative array type. The interface is quite different from both Python’s dict and JavaScript’s objects.
Gotcha: Field Names
If you are trying to assign a new value to an object’s field, be careful. If you mis-spell the field name, you will create a new field instead of changing the one you were trying to target. This can be a nasty source of hard-to-find bugs.
<exercises chapter=”arrays”>
If you need a reminder about random numbers, see JS Random on W3Schools.
- Create a page that prompts the user for 10 numbers and then computes the average value of the numbers entered and reports in an alert box how many of the values entered were above average.
- Create a page with a script that defines an array and puts the string values “Hello”, “World”, and “!” into random array locations between 1 and 10. Then prompt the user for three integers and check to see if they have found the array locations where the three String values are stored. Give them a score out of 3 depending on how many they found and show them the values they uncovered using alert boxes.
- Create a page with a script that defines a lottery ball object. A lottery ball has a field defining its color (randomly set to “red” or “white”) and the number of points it’s worth (random number between 0 and 100). When the ball is created, use an alert box to tell the user the color and value of the ball object that was created. It should be different each time you load the page.
- Modify the script from the last question so that it creates an array of 100 ball objects with random contents. Talk to the user with dialog boxes and allow them to draw balls by entering integers from 0 to 100, until either they draw a red ball or decide to quit. Show them each ball in an alert box. If they draw a red ball, deduct the number of points that ball is worth from their score and end the game. If they draw a white ball, add the number of points to their score and allow them to continue. If they try to draw a ball they drew already, let them try again. When they quit or draw a red ball, show them their total score in an alert box.