How to Run JavaScript
There are two main ways you will be integrating JavaScript into your HTML code:
- Using the
script
tag - Using an external file
This is very similar to CSS, as you can use the <style>
tag or link
an external CSS file.
Below is how you would integrate JavaScript into HTML using the
<script>
tag. The JavaScript code is between the <script>
tags. Examine the code below, then switch to the results tab to see it
run in action.
Showing another way, below is how you would use an external JavaScript file. Examine the JavaScript and HTML files, then switch to the results tab to see it run in action. In CS 204, we will mostly be using external JavaScript files.
JS Console¶
It's nice to be able to try little bits of JS code (just as we might try little bits of Python code by running the Python interpreter). Fortunately, every browser has a JS console (interpreter) built-in so it's easy to test little snippets. I do this all the time.
Getting to the console in Chrome on a Mac:
- At the top bar, go to
view > developer > JavaScript Console
, or Command-Option-J
Getting to the console in Firefox on a Mac:
- At the top bar, go to
tools > web developer > Web Console
, or Command-Option-K
It might look like this:
If you type any Javascript expressions into the console, it will works as well: