- In a browser
- In a headless runtime like Node or Deno.
If we run it in a browser, we can make a web page and have access to the DOM. If we run it in Node, we can build a command line or desktop app.
<!DOCTYPE html> <html> <head> <script src="script.js"></script> </head> <body></body> </html>
It’s also important to note the
</script>. Unlike most tage, script tags cannot be self closing. It’s just one of those browser ideosyncrasies that often trips new coders. It’s an old standard that is now too dificult to change.
In practice, this means you need to type:
<script src="script.js" />
To run the code, just refresh the page.
Exercise - Hello World
- Create a folder in which to work.
- Create a new HTML file in a text editor. Call it index.html.
- Put an alert in the script file, like this: `alert(‘Hello world’)“;
- Open the HTML file in a browser. See the alert?
- Close the alert. Press refresh. The code runs again.
- Extend the code so it pops up two alerts.
If you are running your code in a browser, you will want to be using the developer console. The keyboard shortcut for opening the developer console varies between platforms, but typically you can right click and choos ‘inspect’ from the context menu. From here you can select the console or sources tab. The console shows you everything
To write to the console from your code, use the console.log method. This is excellent for debugging.
Console.log will accept any number of items and any datatype. If you pass it objects and arrays, the console will format these nicely.
We also have console.error, console.info, and a variety of others that will change the formatting of the output. You can change the log level of your console to see different levels of error.
Be sure to remove debugger statments before shipping your code.