Understanding JavaScript for the Java developer

After writing a simple application in a Java tutorial, we now move to the world of JavaScript, contrasting the languages to make the learning process easier.

Because JavaScript is run within a browser, HTML knowledge is required.

In this sixth article in our series on learning modern programming languages, we turn our attention to understanding JavaScript. Implementing the rock-paper-scissors (or roshambo) application using JavaScript is a significant departure from solving our coding problem with either Ruby or Java. JavaScript is not compiled, and it is not run from a command line. Instead, JavaScript runs directly inside a browser, and is re-executed any time the browser is refreshed. Furthermore, because JavaScript is run within a browser, a certain degree of HTML knowledge is required.

The webpage presented to the user for this example (Figure 1) will simply ask the user, "Which one will it be?" and will present three links for the user to click on: rock, paper or scissors.

The roshambo user interface with a prompt and three links.
Figure 1. The roshambo user interface with a prompt and three links.

The well-formed HTML to create this type of display looks like this:

<html>

     <head>

           <title>Roshambo!</title>

           <script>

           </script>

     </head>

     <body>

           Which one will it be?<br/>

           <a href="#" onclick="playRoshambo('rock')">rock</a>

           <a href="#" onclick="playRoshambo('paper')">paper</a>

           <a href="#" onclick="playRoshambo('scissors')">scissors</a>

     </body>

</html>

This code can be entered directly into any standard text editor, saved to the desktop or home directory of your computer, and saved in a file named roshambo.html. After the file is saved, double-clicking on the file will open it up in a browser and the text and the links would appear. Unfortunately, at this point, clicking on the links won't do anything. To get the links to work, we need to add some scripting.

The three links on the page are created using anchor tags, which use the element a and have two key attributes: href and onclick. The href attribute is typically assigned to the URL of a page that will be loaded when the user clicks on the link. Because we want the user to stay on the current page, and not navigate away to somewhere else on the Web, we set the href attribute to the hash sign: #. This makes the page self-referencing.

Instead of navigating to another page when the user clicks on rock, paper or scissors, we want an alert box to appear telling the user the result of playing the game. To make this happen, we hijack the onclick method associated with the link, causing that event to trigger a method named playRoshambo. If the user clicks rock, the text String rock is passed into the playRoshambo method; if paper is clicked, the text String paper is passed in, and the same thing goes for the scissors link. Of course, if we are passing text into a method named playRoshambo, we need to code a method named playRoshambo.

Peppering our HTML page with JavaScript

Understanding JavaScript means knowing it's best to keep within script tags which are embedded within the head tag. The playRoshambo method is a function that takes a single argument, so the method declaration looks like this:

<script>

playRoshambo = function(clientGesture){

}

</script>

As you can see, the text passed into the method is assigned the variable name clientGesture, so it is this variable on which our conditional logic is evaluated. Because there is no possible way bad data could be passed into this method, only three if conditions need to be evaluated. Here's how it looks in JavaScript:

<script>

playRoshambo = function(clientGesture){

     if (clientGesture=='rock') {

           outcome = "tie";

     }

     if (clientGesture=='paper') {

           outcome = "win";

     }

     if (clientGesture=='scissors') {

           outcome = "lose";

     }

     alert("You " + outcome + "!");

}

</script>

Notice the final statement in the method: alert("You " + outcome + "!"). This line of code will trigger a dialog box to appear that displays the game's result (Figure 2).

The roshambo application using a JavaScript alert box.
Figure 2. The roshambo application using a JavaScript alert box.

Here is the full code for our working application:

<html>

     <head>

     <script>

     playRoshambo = function(clientGesture){

           if (clientGesture=='rock') {

                outcome = "tie";

           }

           if (clientGesture=='paper') {

                outcome = "win";

           }

           if (clientGesture=='scissors') {

                outcome = "lose";

           }

           //alert("You " + outcome + "!");

     }

     </script>

     </head>

     <body>

           Which one will it be?<br/>

           <a href="#" onclick="playRoshambo('rock')">rock</a>

           <a href="#" onclick="playRoshambo('paper')">paper</a>

           <a href="#" onclick="playRoshambo('scissors')">scissors</a>

     </body>

</html>

From alert boxes to document model manipulation

Now, if one improvement was to be made to this JavaScript-based game, it would be to eliminate the alert. People hate message boxes, and it just looks ugly in code. Besides, JavaScript is typically used to manipulate components that are displayed on a webpage, so our application should do that as well.

Immediately after the anchor links are coded onto the page, add in a div tag and give it the name result. This creates an area on the page which our JavaScript can hook into and manipulate:

<div id="result"></div>

Then, instead of sending an alert to the user, have the element on the page associated with the id of result render the results. This is achieved by replacing the alert with the following code:

//alert("You " + outcome + "!");

document.getElementById('result')

                                .innerHTML = result;

The refactored roshambo application

The full code for the application looks like this:

<html>

     <head>

     <title>Roshambo!</title>

     <script>

     playRoshambo = function(clientGesture){

           if (clientGesture=='rock') {

                outcome = "tie";

           }

           if (clientGesture=='paper') {

                outcome = "win";

           }

           if (clientGesture=='scissors') {

                outcome = "lose";

           }

           //alert("You " + outcome + "!");

           document.getElementById('result')

                                .innerHTML = outcome;

     }

     </script>

     </head>

     <body>

           Which one will it be?<br/>

           <a href="#" onclick="playRoshambo('rock')">rock</a>

           <a href="#" onclick="playRoshambo('paper')">paper</a>

           <a href="#" onclick="playRoshambo('scissors')">scissors</a>

           <div id="result"></div>

     </body>

</html>

And now, when the application runs, the results are displayed on the page (Figure 3), not through an alert box.

The roshambo application that updates the document model of the webpage.
Figure 3. The roshambo application that updates the document model of the webpage.

And that demonstrates how to code the roshambo application that was originally coded in Java and run on a virtual machine, and port it over to a Web browser by recoding the application using JavaScript and HTML.

So that you know you're understanding JavaScript, replace the existing conditional logic in the roshambo application with some of the additional language constructs that JavaScript makes available for conditional processing, including else and switch statements.

Many new frameworks are pushing for JavaScript on the server side. What has your experience been like moving from Java to JavaScript on the server? Let us know.

Modern programming languages made easy for Java developers

For those interested in learning Java, or for those who know Java and are interested in leveraging those skills in order to learn a complimentary language like JavaScript or Ruby, TheServerSide is providing a number of problem-driven tutorials that will help you master the fundamentals of these languages.

The catalog of tutorials currently includes the following:

Dig Deeper on Core Java APIs and programming techniques