Lesson 13: JavaScript Objects - Arrays

By Maria Antonietta Perna

Just using a few properties and methods of common JavaScript objects has opened your eyes to the amazing things that Object Oriented Programming enables you to accomplish with a few lines of code. In this lesson, you will learn to use what is a very powerful object in most programming languages, including JavaScript of course: the Array object.

In particular, in this lesson you will learn:

  • what the Array object is for;
  • how to create arrays;
  • how to access, sort, add, and remove data inside an array.

In the process, you will learn how to use the for ... in loop to access data inside an array.

What is the Array object for?

An object's job is that of storing and allowing for the easy manipulation of data. We can safely say that the Array object performs both tasks wonderfully.

From the perspective of data storage, an array works a bit like a variable. The difference is that you are not limited to one piece of data, as it's the case with common variables. You can stuff several items at once inside an array and retrieve whichever you need at the right time in your program.

Imagine if you had to have a storage place for each pair of socks. This would be a nightmare! Having a drawer to store all your socks in one place makes much more sense. In this respect, arrays are a bit like drawers, but much more powerful.

From the point of view of data manipulation, the Array object offers a wealth of properties and methods, some of which you will examine in this lesson.

How do you create an Array object?

You create an array in 1 of 3 ways:

1) use new Array()

This is the most verbose approach. It works as follows:

		
		var colors = new Array();
		
		colors[0] = "green";
		
		colors[1] = "red";
		
		

2) use new Array(item0, item1, item2 ...)

This approach also employs the new Array() constructor, but does so using a more concise formulation. Here's what it looks like:

		
		var colors = new Array("green", "red");
		
		

3) use the literal array approach

This is the shortest way of creating and populating an array, and it's the most widely used approach. It looks like this:

		
		var colors = ["green", "red"];
		
		

All 3 approaches illustrated above, create an array object called colors containing 2 string values, "green" and "red" - but arrays can store all other data types: numbers, booleans, even other arrays! The items in our array occupy position 0 and 1 respectively.

As you might have guessed, you count the index position of an item inside an array starting at 0.

But, is this index position important? Well, yes it is, at least if you want to use the items inside the array, which is most likely the case.

Here's what I mean.

How do I access data inside the Array object?

Arrays are great to store several values using only 1 variable. However, they wouldn't be so great if you couldn't also access those values quickly and easily. Here's how it's done:

		
		//"green" is at index position 0, "red" is at index position 1, etc.
		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		var red = colors[1];
		
		document.write(red);
		
		

Enter the code snippet above between enclosing <script> tags in an HTML page, save your work, and run the page in the browser. You should see the word red displayed on the page.

What you did was to access the second value in the colors array by using its index position within the array starting to count at 0.

Access all items in the array with a loop

You might have probably guessed this, but loops and arrays go together like cookies and milk. Here's how you would access all values inside an array by looping over each of them:

		
		//use the array from the previous example
		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		//use a for loop to access each item in colors
		
		//The array object has a length property
		
		//that contains the size of the array: you can use it in the for loop
		
		for (var i=0; i < colors.length; i++)
		
		{
		
		//You use the counter i to access the index position
		
		document.write(colors[i] + "<br />");
		
		}
		
		

Save your file and preview the page in a browser. You should see the color names displayed on the page.

There's also a special type of for loop that you can use with the Array object, the for ... in loop. Here's how it works:

		
		//use the array from the previous example
		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		for (color in colors)
		
		{
		
		//color is the variable that marks the index position
		
		document.write(colors[color] + "<br />");
		
		}
		
		

Run the HTML document containing the code snippet above inside <script> tags in a browser. The web page should look the same as it did in the previous example.

Once you access a value inside an array you can simply retrieve it, as you did in the previous example, or you can modify it, as follows:

		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		colors[2] = "pink";
		
		//Now you've replaced the item at index position 2,
		
		//the third item called "yellow",
		
		//with "pink"
		
		document.write(colors);
		
		//The code should print:
		
		//green,red,pink,orange,blue ("pink" has replaced "yellow")
		
		

Can I sort array items?

You can do amazing stuff with values stored inside an array. For example, you can sort items alphabetically, in descending or ascending order, or numerically. Let's see how this is done.

You sort array elements with a fantastic method most appropriately called sort(). Here it is in action:

		
		//sort the colors array alphabetically and ascending:
		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		var ascendingColors = colors.sort();
		
		//display each value
		
		document.write(ascendingColors);
		
		//This should print:
		
		//blue, green, orange, red, yellow
		
		

If you want to sort numerical values inside an array, either in ascending or descending order, you need to build a simple custom function and pass this function as argument to the sort() method. It sounds a bit harder than it actually is. Here's how it's done:

		
		//build a new array containing number values
		
		var myNumbers = [4, 2, 10, 6, 9];
		
		//build your custom function: this is a simple formula
		
		function sortAscending(a, b)
		
		{
		
		//the formula return a - b sorts the numbers
		
		//from the smaller to the bigger,
		
		//the formula return b - a sorts numbers in descending order,
		
		//that is, from the bigger to the smaller number
		
		return a - b;
		
		}
		
		//pass the sortAscending function as argument to sort()
		
		var sortedAscending = myNumbers.sort(sortAscending);
		
		//print result on the page
		
		document.write(sortedAscending);
		
		//This should print:
		
		//2,4,6,9,10 .  Now try sorting in descending order on your own.
		
		

How do I add data to the Array object?

You can add new items inside an array in different ways. Which method you choose depends largely on your program's requirements.

Add items to the end of the array with push()

What feels more like the natural order of things, that is, adding an item to the end of an array, is easily achieved using the push() method. Here's how it works:

		
		//use our old colors array
		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		//use push() to add the color "pink" at the end
		
		colors.push("pink");
		
		//print the enlarged array
		
		document.write(colors);
		
		//This should print:
		
		//green,red,yellow,orange,blue,pink
		
		

Add items to the beginning of an array with unshift()

Use unshift() to add new items to the start index position of an array. This is easily done.

Just replace push() with unshift() in the previous example, save your work and run the page in a browser. The page should display the color name "pink" at the very start, like so:

pink,green,red,yellow,orange,blue.

How do I remove data from the Array object?

If you want to remove the last item in an array you use pop(). If you want to remove the first item in an array you use shift().

		
		var colors = ["green", "red", "yellow", "orange", "blue"];
		
		//remove "blue" from colors
		
		colors.pop();
		
		document.write(colors);
		
		//This prints: green,red,yellow,orange
		
		
		
		//remove "green" from colors
		
		colors.shift();
		
		document.write("<br />" + colors);
		
		//This prints: red,yellow,orange
		
		//on a new line break
		
		

Have fun experimenting with the examples above and come back to our try out challenge as soon as you're ready.

Try out: Username registration

You will build a mock Username registration program with the following requirements:

  • the user can enter a Username in the inputbox, and click a button to register;
  • if the Username already exists, the program informs the user;
  • if the Username is not already stored in the program, the new Username is added, the user is informed, and all stored Usernames are displayed on the page in alphabetical order.

A real registration program would ask for more information, the data would be permanently stored in a database, and existing Usernames would never be printed out for everybody to see.

However, this is a mock application: our Usernames are stored in a global array. This ensures that the values inside will be accessible from any function in the script, and the newly added Usernames will be preserved for as long as the program runs. Displaying the Usernames on the page will show the workings of the global variable (see Lesson 4 for a refresher on global variables) as well as of the array methods push() and sort().

Enough talking, let's get coding! Prepare an HTML page with an inputbox, a button, and a paragraph to display messages to the user. Make sure each element has an id value so that your code can have an easy handle on them.

The HTML document

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 13: JavaScript Objects - Arrays</title>
		<script type="text/javascript" src="lesson13_tryout.js"></script>
		</head>
		<body>
		<h1>Lesson 13: Register with us</h1>
				
		<p>Register a Username: <input type="text" id="txtName" /></p>
			
		<p><input type="button" id="btnSubmit" value="Register" /></p>
			
		<p id="result"></p>
				
		</body>
		</html>
		
		

The JavaScript file: lesson13_tryout.js

Your program contains:

  • a global array called userNames used to store Usernames;
  • a function called init() used to bind the main function to the onclick event of the button;
  • and a function called registerName() that performs all the main program tasks.
		
		//global array: it's outside any function
		
		var userNames = ["harry potter", "donald duck", "shrek", "supercoder"];
		
		
		/*******************************/
		
		
		//init() function
		
		function init()
		
		{
		
		var myButton = document.getElementById("btnSubmit");
		
		myButton.onclick = registerName;
		
		}
		
		
		//assign init() function to onload event
		
		onload = init;
		
		
		
		/********************************************/
		
		
		
		//registerName() function: it executes when user clicks the button
		
		function registerName()
		
		{
		
		//set up main vars: Username entered by user,
		
		//a message string to communicate with the user,
		
		//a reference to the paragraph used to display the message,
		
		//and a boolean var (true/false) used as flag:
		
		//if the registration is successful, this is set to true,
		
		//if registration fails, this is set to false. It's initialized as false.
		
		//Notice how you chain getElementById(), value, and toLowerCase
		
		//to store the value entered by the user in lowercase
		
		var newName = document.getElementById("txtName").value.toLowerCase();
		
		var message = "";
		
		var result = document.getElementById("result");
		
		var success = false;
		
		//If the user clicks the button but the inputbox is empty
		
		//we alert the user and stop further program execution:
		
		if (newName == "")
		
		{
		
		alert("Please, enter a Username");
		
		return false;
		
		}
		
		//we loop over each Username stored in the array
		
		//to make sure the Username is not already in existence
		
		for (var i = 0; i < userNames.length; i++)
		
		{
		
		//if we find a Username equal to the newly entered name,
		
		//it means the Username already exists and we can't
		
		//proceed with registration
		
		if (userNames[i] == newName)
		
		{
		
		message = "Sorry, the Username " + userNames[i] + " already exists.  Try again";
		
		result.innerHTML = message;
		
		//set the success flag to false so the rest of the program knows
		
		//that registration failed
		
		success = false;
		
		//stop further program execution
		
		return false;
		
		}
		
		//else - if the Username entered by the user
		
		//is not already stored in the application, register new user:
		
		else
		
		{
		
		message = "Great, you've successfully registered with us as " + newName;
		
		result.innerHTML = message;
		
		//set the success flag to true, so the program knows
		
		//the new Username can be added
		
		success = true;
		
		}
		
		}
		
		//Now you're out of the loop
		
		//if registration was successful (success flag is true),
		
		//add new Username to the array with push()
		
		if (success)
		
		{
		
		userNames.push(newName);
		
		}
		
		//display Usernames sorted alphabetically on a new line
		
		result.innerHTML += "<br />" + userNames.sort();
		
		}
		
		

Save all your files and run the HTML document in a browser. You should see something similar to the example page indicated by following the link above.

Try clicking the button without entering anything in the inputbox, then enter a Username already present in the array - for example, supercoder - and try to register; finally, enter a new name and see it getting added to the array. As you enter new names, these get added to the array and displayed alphabetically.

Summary

You've worked really hard in this lesson, well done! You're now familiar with the Array, a powerful JavaScript object, and some of its fantastic methods. You can also use a for in loop to access array values, and you've built a challenging little demo application.

Take your well-deserved break, the next topic awaits you: get ready for an exploration of the very environment that makes JavaScript possible, the browser.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 12: JavaScript Objects: Math Object

Lesson 14: JavaScript Living Space - the Browser Environment >>