Programming on the Client Side
17 JavaScript Arrays and Objects
Learning Outcomes
When you have completed this chapter, you will be able to:
- Describe JavaScript’s flexible approach to arrays and array literals.
- Explain the relationship between objects, object literals, and associative arrays in JavaScript.
- Write simple JavaScript programs using arrays, objects, and arrays of 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:
const 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?
The following pieces of code creates an empty array.
const a = [];
You can also create an array with some initial contents, like this:
const 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.
const 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.
const 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?
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.
Constant Arrays
You may have noticed that in some of the examples above, instead of using let to declare arrays, const was used. You may have also subsequently noticed that in some of the Do It Yourself boxes above, despite the array being declared as a constant, its elements were modified. This is possible because the array object itself does not store the elements assigned and is rather a reference to the elements. This is similar to how arrays in C/C++ are just pointers to the memory address where the elements are stored.
const names = ["Sam", "Scott"]; // valid operations names.push("Jack"); names[0] = "Bob"; // invalid operation names = ["Sam"];
In the example above, we can clearly see how constant arrays can have their elements modified, added, and removed however, the array itself cannot be redeclared. This is because the reference has already been declared as a constant in the same block-level scope.
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 the argument “Cool”.
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 by using an object literal 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. The code in braces is an object literal.
const 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. Additionally, since objects are stored as reference variables, they are usually declared as constants if you don’t plan to reassign the variable.
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.
Check Your Understanding
Coding Practice
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 99 (corresponding to an array index), 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, or an invalid ball (less than 0, larger than 99) let them try again. When they quit or draw a red ball, show them their total score in an alert box.
Feedback/Errata