Because JavaScript is run within a browser, HTML knowledge is required.
In this sixth article in our serieson learning modern programming languages, we turn our attention to understanding JavaScript. Implementing the rock-paper-scissors (orroshambo) 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.
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="#">rock</a>
<a href="#">paper</a>
<a href="#">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 elementa and have two key attributes:href andonclick. Thehref 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 thehref 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 theonclick method associated with the link, causing that event to trigger a method namedplayRoshambo. If the user clicks rock, the text Stringrock is passed into theplayRoshambo method; if paper is clicked, the text Stringpaper is passed in, and the same thing goes for the scissors link. Of course, if we are passing text into a method namedplayRoshambo, we need to code a method namedplayRoshambo.
Understanding JavaScript means knowing it's best to keep withinscript tags which are embedded within thehead tag. TheplayRoshambo 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 nameclientGesture, 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 #"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).
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="#">rock</a>
<a href="#">paper</a>
<a href="#">scissors</a>
</body>
</html>
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 adiv tag and give it the nameresult. This creates an area on the page which our JavaScript can hook into and manipulate:
<div></div>
Then, instead of sending an alert to the user, have the element on the page associated with theid ofresult render the results. This is achieved by replacing the alert with the following code:
//alert("You " + outcome + "!");
document.getElementById('result')
.innerHTML = result;
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="#">rock</a>
<a href="#">paper</a>
<a href="#">scissors</a>
<div></div>
</body>
</html>
And now, when the application runs, the results are displayed on the page (Figure 3), not through an alert box.
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 arepushing for JavaScript on the server side. What has your experience been like moving from Java to JavaScript on the server?Let us know.
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:
An ADR is only as good as the record quality. Follow these best practices to establish a dependable ADR creation and maintenance ...
At some point, all developers must decide whether to refactor code or rewrite it. Base this choice on factors such as ...
API proxies and gateways help APIs talk to applications, but it can be tricky to understand vendor language around different ...
A principal engineer says Postman's Spec Hub will help the company shift to a spec-first API development process for its ...
AWS Kiro, a project developed by a 'small, opinionated team within AWS,' prioritizes spec-driven development in the workflows of ...
Docker is expanding the Docker Compose spec to accommodate AI agents in an effort to bring AI development closer to existing ...
AI is transforming PaaS with automation and cost-efficient features, but will it eventually replace cloud platforms? Industry ...
Even though Q-Day might be several years away, enterprises should develop a strategic plan to prepare for the future. Experts ...
Businesses can find security vulnerabilities when they push their workloads to the edge. Discover the pitfalls of cloud edge ...
Runtime security and tokenization stand to play a bigger role in attack surface management, a development that could influence ...
How CISOs design and build their security teams is as important as the technology they select to safeguard their organizations' ...
Calculating and communicating cybersecurity ROI can help persuade top management to invest. Here's how to use meaningful, ...
Compare Datadog vs. New Relic capabilities including alerts, log management, incident management and more. Learn which tool is ...
Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates ...
There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service ...