Goal

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.

Introduction

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.

How it Works

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…

Different Environments are Different

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:

CleanShot 2024-11-10 at 12.01.20@2x.png

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.

CleanShot 2024-11-10 at 12.05.02@2x.png

Let’s open the console and see what’s going on:

CleanShot 2024-11-10 at 12.31.23@2x.png

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>