Goal: Continue to practice writing JavaScript functions by beginning the business logic for a calculator app. Later, we'll add user interface logic too, and familiarize ourselves with the differences between code for each, and how to keep them separated and organized.
Follow along with the previous lesson to begin building a calculator app. Once you've written the code detailed in that lesson, create a project and migrate your code from JSFiddle into VS Code by doing the following:
calculator
project folder on your computer.js
and css
folders in your project folder.scripts.js
file in your project's js
subdirectory.scripts.js
file to save it.<script src="js/scripts.js"></script>
(see below for example html file)<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<script src="js/scripts.js"></script>
</body>
</html>
function add(number1, number2) {
return number1 + number2;
}
const number1 = parseInt(prompt("Enter a number:"));
const number2 = parseInt(prompt("Enter another number:"));
const result = add(number1, number2);
alert(result);
If you open your HTML file in the web browser, it should run your code just like it did on JSFiddle; popping up prompt boxes for input and then an alert with the calculated result. If this isn't working, check that you correctly link to your scripts file and that your scripts file includes both the add() function and code that actually calls that function. If something on your page isn't working right, an excellent initial troubleshooting step is to check the JavaScript console to see if there are any helpful error messages that might point you in the right direction.
Next, create functions to subtract, multiply, and divide. Verify that all four work by changing the line near the bottom of the scripts.js (currently reads const result = add(number1, number2);
) to call different functions. For now you must manually change that line to choose between operations. In upcoming lessons we'll build a user interface for our calculator so that the user can choose between addition, subtraction, multiplication and division. Do not build out the user interface yet. For now just focus on the business logic.
(You can do these in JSFiddle.)
If you fully complete the exercise above continue onward to work through tonight's homework, and the Bonus Function Writing exercise following it.
Lesson 7 of 19
Last updated December 1, 2020