Goal: Continue to practice writing JavaScript functions by creating the calculator app.
window.prompt()
?<script>
tag do?Create the calculator project that we walked through in the previous lessons. Below are the setup instructions as well as the sample HTML and JS code we used in the walkthrough. Reference the previous lessons as needed.
calculator
project folder on your computer.js
and css
folders in your project folder.scripts.js
file in your project's js
subdirectory.styles.css
file in your project's css
subdirectory.index.html
in the root of your project directory, using the HTML below.scripts.js
file: <script src="js/scripts.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel="stylesheet" href="css/styles.css" type="text/css">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
</body>
</html>
// business logic
function add(number1, number2) {
return number1 + number2;
}
// user interface logic
const number1 = prompt("Enter a number:");
const number2 = prompt("Enter another number:");
window.alert(add(number1, number2));
When you open your HTML file in the web browser, it runs all scripts connected to it. If you run the project with the starter code above, you should see two prompts for numbers, and then an alert with the calculated result. If the project isn't working:
subtract
, multiply
, and divide
two numbers. window.alert(...);
method calls to include a phrase that explains the result. For example, when calling the add()
function and getting an 8
as a result, the alert should say something like "The addition of your numbers equals 8". Do this for every function.window.alert()
method calls into one call that states all of the results of each mathematical operation. For example, if the user inputted numbers are 2 and 1, the alert should say: "The addition of your numbers equals 3. The subtraction of your numbers equals 1. The multiplication of your numbers equals 2. The division of your numbers equals 2."
In upcoming lessons, we'll learn how to make forms in HTML that can gather user input and streamline our calculator applications even more!