You have already built a simple command-line calculator in lesson 1. Let’s now adapt that calculator to the web. This will give you a basic GUI calculator running in a web page! You can even put it online and share it with your friends.
You can run JavaScript in many environments. You have already seen JavaScript running in a command line environment using Node.js
. Another environment you can run JavaScript inside is web pages. Here is the very simplest JavaScript program in a web page:
<script>
alert("hello, world!");
</script>
To run this program, copy it into a file like calc.html
and then drag the file onto a web browser like Chrome or Safari.
The alert
function is a built-in function in web browsers that pops open a dialog box. There are other built-in functions you can try like confirm
or prompt
. You can check with ChatGPT to see how those work and play with them.
Inside the <script>
element you can put a whole JavaScript program. For example, you could copy your whole previous calc.js
command-line program into this script element, except…
If you try putting the contents of calc.js
into this <script>
tag and running it you’ll get a blank white screen, like this:
Why doesn’t it work?
Different environments run JavaScript differently. One things that’s different is how you see errors. In Node.js errors get printed out to the terminal. But in web browsers, errors go into a special tool called the javascript console. How you open the console varies by which web browser you use.
On Chrome you use the view -> developer -> javascript console
menu item. You can use Google or ChatGPT to figure out how to do it in other browsers.
Let’s open the console and see what’s going on:
aha! What’s happening here is another difference between JS environments: in order to use the import
statement in web browsers you need a different script tag. Let’s fix it:
<script type="module">
// copy calc.js program here
</script>