Home Store Project Ideas Project Guide Ask An Expert Blog Careers Teachers Parents Students

ABC's of Programming: Writing a Simple 'Alphabetizer' with JavaScript

Difficulty
Time Required Short (2-5 days)
Prerequisites Familiarity with Web browser and text editing programs
Material Availability Readily available
Cost Very Low (under $20)
Safety No issues

Abstract

This is a good first-time programming project. You'll learn how to use JavaScript to create a simple program to alphabetize lists of words. You'll be able to run your program in your Web browser.

Objective

The objective of this project is to write a JavaScript program to alphabetize a list of words.

Credits

Andrew Olson, Ph.D., Science Buddies

Cite This Page

MLA Style

Science Buddies Staff. "ABC's of Programming: Writing a Simple 'Alphabetizer' with JavaScript" Science Buddies. Science Buddies, 18 Mar. 2014. Web. 1 Sep. 2014 <http://www.sciencebuddies.org/science-fair-projects/project_ideas/CompSci_p002.shtml?from=Blog>

APA Style

Science Buddies Staff. (2014, March 18). ABC's of Programming: Writing a Simple 'Alphabetizer' with JavaScript. Retrieved September 1, 2014 from http://www.sciencebuddies.org/science-fair-projects/project_ideas/CompSci_p002.shtml?from=Blog

Share your story with Science Buddies!

I did this project I Did This Project! Please log in and let us know how things went.


Last edit date: 2014-03-18

Introduction

This is an example of a first-time programming project. You will be writing a simple program that can alphabetize a list of words. The project uses JavaScript, an interpreted programming language supported by most Web browsers. You will learn how to write an HTML file containing your program, and how to load and run the file in your browser.

In this project, you will learn the basics of how JavaScript functions can be written to work with HTML FORM elements. Specifically, you will be working with HTML TEXTAREA and INPUT elements, and using JavaScript String and Array objects in your functions. The more advanced variations of this project (see Possible Variations section, below) may require "if...then" and/or "for" or "while" loop control statements.

Preliminaries These are things you need to know before you get started.
  1. You'll need to write your file with a text editor, which is a program that can save plain text files. The "Notepad" program that comes with Windows will do just fine. You should not use a word processing program (e.g., Word), because word processors do not save files as plain text by default.
  2. JavaScript is a programming language for web pages, so the HTML file you will be writing is like a simple web page. Here is the basic format of an HTML file: <!-- comment line: ignored by browser, use these as notes to yourself about your program -->
    <HTML>
    <HEAD>
            [Title and JavaScript functions go here.]
    </HEAD>

    <BODY>
            [The parts you want to appear on the page go here.]
    </BODY>
    </HTML>

    HTML uses tags to designate various parts of the document. Tags are enclosed by the characters "<" (less-than sign) and ">" (greater-than sign). The first line is a comment, enclosed by "<!--" and "-->". Comments in an HTML file are ignored by the browser, so you can use them as notes to yourself. They can help you remember what the different parts of your program are supposed to do. You need the tag "<HTML>" at the beginning. The document has two sections, a HEAD section, which contains general information about the document, and a BODY section which contains the displayed material. The HEAD section is where you would specify the title of the document, and also where you would put JavaScript functions used in the document. The end of the HEAD section is indicated by the end tag, "</HEAD>". Next comes the BODY section, with material that you wish to appear on the page. It is ended by the end tag "</BODY>". Finally, the end of the document is indicated by the HTML end tag, "</HTML>". The same pattern applies to all HTML tags: the end tag is made by adding "/" (the forward slash character) to the beginning of the corresponding start tag.
  3. For practice, try using your text editor to write a very simple HTML file like the one below. (You can write it yourself, or you can copy and paste from your browser to your text editor.)

    <!-- Science Buddies: HelloWorld.html -->
    <HTML>
    <HEAD>
       <TITLE>Hello, world!</TITLE>
    </HEAD>

    <BODY>
       Hello, world!
    </BODY>
    </HTML>
  4. Use your text editor to save the file. Call it something like "HelloWorld.html" (when choosing a name for your file, always end the name with ".htm" or ".html").
  5. Now open your HelloWorld.html file with your browser. In your browser, use the "File" menu, and choose the option "Open..." (for Firefox, choose "Open File..."). Using the controls in the File Open dialog box that pops up, navigate to your file and select it. In Windows, you can also open the file by right-clicking it, selecting "Open with..." and then choosing a web browser from the list of available programs. You should see "Hello, world!" on both the browser title bar and on the body of the page.
Getting Started with JavaScript

Now that you've succeeded with writing an HTML file and opening it with your browser, you're ready to delve into JavaScript. The following link has a step-by-step tutorial that will give you a great introduction to JavaScript programming: http://www.webteacher.com/javascript/index.html

After you've studied the JavaScript tutorial, you should be almost ready to try your hand at writing a JavaScript sorting program. Before you go on, test your basic HTML and JavaScript knowledge. See how many terms, concepts and questions you know in the "Terms, Concepts and Questions to Start Background Research" section below.

Writing a JavaScript Program to Alphabetize a List

To help get you started, here is an example of the kind of program we have in mind. This is just one of many ways to accomplish this task. You can use this example as a basis for your program, or you can start from scratch.

Simple Sorter

Type or paste a list of words, separated by spaces, into the box below, then press the "Alphabetize Words" button to have the list sorted alphabetically.

   

There are five more pieces which you will need to understand in order to write this program:

  1. the <TEXTAREA> object, which you can use in an HTML <FORM>.
  2. the .split() method of the built-in JavaScript String object, which you can use to break a string into smaller pieces. (It's the converse of the .join() method, below.)
  3. the Array, a built-in JavaScript object for storing and manipulating lists of things.
  4. the .sort() method of the built-in JavaScript Array object, which you can use to put the array elements into a particular order.
  5. the .join() method of the built-in JavaScript Array object, which you can use to put all of the elements in an Array into a single string. (It's the converse of the .split() method, above.)

1. You'll use two TEXTAREA objects in your HTML FORM, one for the user to input the list of words, and one for the program to output the alphabetized list. Here are two examples:

<TEXTAREA name="inputText" rows=5 cols=80 wrap=on></TEXTAREA>
<TEXTAREA name="outputText" rows=5 cols=80 wrap=on readonly></TEXTAREA>

First of all, note that TEXTAREA has both a start tag and an end tag. Any text appearing between these tags will show up in the TEXTAREA on the form. We've given each TEXTAREA a name (corresponding to its function), and we've specified the size of the TEXTAREA, in terms of rows (rows=5) and columns (cols=80) of text. We've set both TEXTAREAs to automatically wrap long lines of text (they will be broken only where whitespace occurs). The TEXTAREA for the output has been set "readonly", which means that the user can only read, but not enter, text here. To access the text contained in a TEXTAREA object, you use the object's ".value" property, which contains the text as a single JavaScript String object. For example, the user input text would be obtained with: "s = inputText.value", where s is a String object.

2. OK, so now you know how to use the TEXTAREA object to let your program handle chunks of text. Now you need to know the built-in JavaScript tools for turning chunks of text into lists that you can manipulate. JavaScript String objects have a built-in .split() method which you can use to break a string into smaller pieces. The .split() method has a single argument, the separator character to use for breaking up the string. In the example above, we asked the user to type or paste a list of words separated by spaces. So when we want to split the block of text into separate words, we would call the .split() method like this:
inputText.value.split(" ");
The quotation marks enclose a single space character, so the input text string will be split at each occurrence of a space. And where does all of the split text end up?

3. In an Array, naturally. The .split() method returns an Array object. An Array is a built-in JavaScript object type that you can use for handling lists. Most programming languages have a similar feature. In general, an array is simply a series of elements. You can access an individual element in the array by using it's index in the array. The first array element has an index of 0, the second element has an index of 1, and so on. If your array was named inputTextArray, the individual elements would be written like this in JavaScript:
inputTextArray[0]
inputTextArray[1]
inputTextArray[2]
etc.

An Array object has a .length property that tells you how many elements are in the array. Remember that array index numbers start with 0, so the index of the last element in an array will be the array length minus 1. So to access the last element in our example array, we could write:
inputTextArray[inputTextArray.length - 1]

4. The JavaScript Array object has two methods that will be useful for this project: .sort() and .join(). By default, the .sort() method will compare the array elements as strings, sorting them in lexicographic ("dictionary" or "telephone book") order. So, for a first pass, calling the .sort() method with no argument will put our input array into order. (See the Possible Variations section, below, for some improvements you can make.)

5. Finally, we need to get the alphabetized word list back into the form of a single string in order to put it in the output TEXTAREA. The .join() method comes in handy here. The .join() method has a single argument, the separator character, which separates the individual elements as they are placed into a single output string. It's the converse of the .split() method for strings, which we discussed previously. You can figure out how to call the .join() method by analogy.

Now you've seen all the pieces, you just need to put them together. Have fun writing your sorting program!

Note for JavaScript files with Internet Explorer:
If you experience difficulty running your JavaScript code in Internet Explorer, we strongly suggest that you install the Firefox web browser and use it instead of Internet Explorer. For more information or to download the Firefox installer, see: http://www.mozilla.com/firefox/.

If you want to continue to use Internet Explorer, try adding the following line at the beginning of your file:
<!-- saved from url=(0014)about:internet --> This line will cause Internet Explorer to run your file according to the security rules for the Internet zone on your computer. In our experience this may work, or it may not. For more information see http://www.phdcc.com/xpsp2.htm.

Terms and Concepts

To write a simple program in JavaScript, you should do research that enables you to understand the following terms and concepts:

  • HTML concepts:
    • start tags and end tags,
    • comments,
    • the <HEAD> section,
    • the <SCRIPT> section,
    • the <BODY> section,
    • the <FORM> section,
    • the <INPUT> tag,
    • the <TEXTAREA> tag.
  • JavaScript concepts:
    • functions,
    • variables,
    • objects,
    • properties,
    • methods,
    • events,
    • arrays.
  • specific JavaScript methods:
    • .split(), a String object method for separating text into arrays,
    • .join(), an Array object method for joining all of an array's elements into a single string,
    • .sort(), for sorting arrays.
  • general programming concepts:
    • reserved words,
    • control statements (e.g., if...else statements, for loops).

Questions:

  • How do you use a TEXTAREA object in an HTML form to get one or more lines of input from the user and store it in a variable?
  • How do you program a button in an HTML form to call a JavaScript function?
  • How do you pass information from an HTML form to a JavaScript function using a variable?
  • How do you program a JavaScript function to display information in an HTML form?
  • How do you use the JavaScript String object's .split() method to break a chunk of text into an array of separate words?
  • How do you use the JavaScript Array object's .sort() method to arrange an array of words in alphabetical order?
  • How do you use the JavaScript Array object's .join() method to create a single text string containing all the elements in the array?

Bibliography

  • You can find a step-by-step JavaScript tutorial at the link below. After studying the tutorial, you should be able to answer all of the questions listed above, and you'll be ready to write a simple calculator.
    Webteacher Software. (2006). JavaScript Tutorial for the Total Non-Programmer. Webteacher Software, LLC. Retrieved June 6, 2006, from http://www.webteacher.com/javascript/index.html http://www.webteacher.com/javascript/index.html
  • Introduction to Programming by Matt Gemmell describes what programming actually is:
    Gemmell, M. (2007). Introduction to Programming. Dean’s Director Tutorials & Resources. Retrieved March 14, 2014, from http://www.deansdirectortutorials.com/Lingo/IntroductionToProgramming.pdf
  • HTML Forms reference:
    W3C. (1999). Forms in HTML Documents, HTML 4.01 Specification. World Wide Web Consortium: Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University. Retrieved June 6, 2006, from http://www.w3.org/TR/REC-html40/interact/forms.html
  • A list of reserved words in JavaScript (you cannot use these words for function or variable names in your program, because they are reserved for the programming language itself):
    JavaScript Kit. (2006). JavaScript Reserved Words. Retrieved June 6, 2006, from http://www.JavaScriptkit.com/jsref/reserved.shtml
  • A JavaScript reference:
    Mozilla Developer Network and Individual Contributors. (2013, December 14). JavaScript reference. Retrieved March 14, 2014, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
  • If you get interested and start doing a lot of web development, you may want to use a text editor that is a little more sophisticated than Notepad. An editor designed for web development and programming can help with formatting so that your code is more readable, but still produce plain text files. This type of editor can also fill in web-specific HTML coding details and do "syntax highlighting" (e.g., automatic color-coding of HTML), which can help you find errors. One option is the CoffeeCup HTML Editor, which is available in the following formats:

Materials and Equipment

Experimental Procedure

Using what you have learned about programming in Javascript, create a program that can alphabetize a list of words.

Here are some generally applicable programming tips to keep in mind as you get started with this project.
  1. Plan your work.
    • Methodically think through all of the steps to solve your programming problem.
    • Try to parcel the tasks out into short, manageable functions.
    • Think about the interface for each function: what arguments need to be passed to the function so that it can do its job?
  2. Use careful naming, good formatting, and descriptive comments to make your code understandable.
    • Give your functions and variables names that reflect their purpose in the program. A good choice of names makes the code more readable.
    • Indent the statements in the body of a function so it is clear where the function code begins and ends.
    • Indent the statements following an "if", "else", "for", or "while" control statement. That way you can easily see what statements are executed for a given branch or loop in your code.
    • Descriptive comments are like notes to yourself. Oftentimes in programming, you'll run into a problem similar to one you've solved before. If your code is well-commented, it will make it easier to go back and re-use pieces of it later. Your comments will help you remember how you solved the previous problem.
  3. Work incrementally.
    • When you are creating a program, it is almost inevitable that along the way you will also create bugs. Bugs are mistakes in your code that either cause your program to behave in ways that you did not intend, or cause it to stop working altogether. The more lines of code, the more chances for bugs. So, especially when you are first starting, it is important to work incrementally. Make just one change at a time, make sure that it works as expected and then move on.
    • With JavaScript, this is easy to do. To check your code, all you need to do is use your web browser to open the HTML file containing your code. After you've made a change in the code with your text editor, just save the file, then switch to your browser and hit the re-load page button to see the change in action.
    • Test to make sure that your code works as expected. If your code has branch points that depend on user input, make sure that you test each of the possible branch points to make sure that there are no surprises.
    • Also, it's a good idea to backup your file once in awhile with a different name. That way, if something goes really wrong and you can't figure it out, you don't need to start over from scratch. Instead you can go back to an earlier version that worked, and start over from there.
    • As you gain more experience with a particular programming environment, you'll be able to write larger chunks of code at one time. Even then, it is important to remember to test each new section of code to make sure that it works as expected before moving on to the next piece. By getting in the habit of working incrementally, you'll reduce the amount of time you spend identifying and fixing bugs.
  4. When debugging, work methodically to isolate the problem.
    • We told you above that bugs are inevitable, so how do you troubleshoot them? Well, the first step is to isolate the problem: which line caused the program to stop working as expected? If you are following the previous tip and working incrementally, you can be pretty sure that the problem is with the line you just wrote.
    • Check for simple typos first. A misspelled function name will not be recognized. In JavaScript, a misspelled variable name simply creates a new variable. This is an easy mistake to make, and can be hard to find.
    • Avoid using reserved words as variable or function names.
  5. Test your program thoroughly.
    • You should test the program incrementally as you write it, but you should also test the completed program to make sure that it behaves as expected.

Share your story with Science Buddies!

I did this project I Did This Project! Please log in and let us know how things went.


Variations

  • For a more basic project, see: Forms and Functions: Writing a Simple Calculator Program with JavaScript.
  • In the example sort program above, try including Some Capitalized Words in your list, along with all-lowercase words. What happens? The ".sort()" method uses the ASCII code values for characters to sort the words (see: Table of ASCII Characters ). Capital letters and lower-case letters are not equivalent in this sorting scheme. How can you change the program so that it ignores the case of the letters?
  • The JavaScript .sort() method for Array objects works well for sorting strings alphabetically. Try sorting the following sequence of numbers, though, and see what happens (you can copy and paste them into the Simple Sorter, above): " 10 8 27 1345 90 ". The .sort() method can be enhanced by including a comparison function as an argument. The comparison function has the form: "compareFunction(a, b)", that is, it takes two arguments, which are the two array elements that are to be compared. If element a should be sequenced before element b, the comparison function should return a value less than 0. If element a should be sequenced after element b, the comparison function should return a value greater than zero. If the elements are equal in terms of sequence order, the comparison function should return 0. As an example, if you wanted to sort in reverse alphabetical order, you could use the following function:
    function reverseStrings(a, b)
    {
       if(a > b)      //a comes after b, alphabetically
          return(-1); //so sequence it earlier
       if(a < before="" b,="" alphabetically       return(1);  //so sequence it later
       return(0);
    }
    Write a comparison function that will sort numbers properly.
  • The JavaScript .split() method for separating text is quite limited. For example, there can be only a single pattern for word breaks, but words in ordinary text are separated by both spaces and punctuation marks. Write your own splitWords() function to take a paragraph of ordinary text as input and create an array of words as output. The array entries should contain strings of letters only—no whitespace characters! You'll need to learn how to write a loop using the JavaScript "for" or "while" statement. You can look it up in the JavaScript reference, and you can also study the next JavaScript programming project, on counting words: Paragraph Stats: Writing a JavaScript Program to "Measure" Text

Share your story with Science Buddies!

I did this project I Did This Project! Please log in and let us know how things went.

Ask an Expert

The Ask an Expert Forum is intended to be a place where students can go to find answers to science questions that they have been unable to find using other resources. If you have specific questions about your science fair project or science fair, our team of volunteer scientists can help. Our Experts won't do the work for you, but they will make suggestions, offer guidance, and help you troubleshoot.

Ask an Expert

Related Links

If you like this project, you might enjoy exploring these related careers:

Computer programmer typing on a keyboard

Computer Programmer

Computers are essential tools in the modern world, handling everything from traffic control, car welding, movie animation, shipping, aircraft design, and social networking to book publishing, business management, music mixing, health care, agriculture, and online shopping. Computer programmers are the people who write the instructions that tell computers what to do. Read more
NASA flight software engineer

Computer Software Engineer

Are you interested in developing cool video game software for computers? Would you like to learn how to make software run faster and more reliably on different kinds of computers and operating systems? Do you like to apply your computer science skills to solve problems? If so, then you might be interested in the career of a computer software engineer. Read more
Software quality engineer working on database

Software Quality Assurance Engineer & Tester

Software quality assurance engineers and testers oversee the quality of a piece of software's development over its entire life cycle. Their goal is to see to it that the final product meets the customer's requirements and expectations in both performance and value. During the software life cycle, they verify (officially state) that it is possible for the software to accomplish certain tasks. They detect problems that exist in the process of developing the software, or in the product itself. They try and make things not work (try to "break" the software) by creating errors or combinations of errors that a user might make. For example, if a user enters a period or a pound sign for a password, will that break the software? They seek to anticipate potential issues with the software before they become visible. At the end of the life cycle, they reflect upon how problems or bugs arose, and figure out ways to make the software development process better in the future. Read more

Looking for more science fun?

Try one of our science activities for quick, anytime science explorations. The perfect thing to liven up a rainy day, school vacation, or moment of boredom.

Find an Activity