How to Run JavaScript
There are 3 major ways to run JavaScript code.
- Browser JavaScript console. Most easy way to learn JavaScript.
- In HTML file in a browser. Web apps are done this way.
- Deno js, run in terminal. Most versatile, flexible, powerful. Used by all professional web dev coders.
Following are details of each.
Browser JavaScript Console
A good way to learn JavaScript is to run it in browser's JavaScript console.
See: How to Use Browser Console .
Embedding JavaScript in HTML
The normal way for JavaScript to run, is to embed JavaScript code in a HTML file and view the file in browser. This is how web applications are written.
Here is how to embed JavaScript into HTML. Put the following into a file:
<script> alert("hi!"); </script>
You should put this near the end of the HTML file, right above the close body
tag.
For example, name the file xtest.html
. Then, open it in a browser.
Modern Way to Embed JavaScript
Modern way, since about 2010, is to put the JavaScript code in a file, and link to it, like this:
<script defer src="xtest.js"></script>
you can place this anywhere inside the HTML head
tag, or anywhere inside in body
tag.
- Create a file named
xtest.html
, with the above content. - Create a file named
xtest.js
, with the contentalert("hi2");
. - Open the file
xtest.html
in browser.
Note: older tutorial may have type
attribute like this:
<script type="text/javascript" src="x.js"></script>
But it is not necessary since around year 2010 with html5.
Using Deno
Using node.js
Alternative to deno is node.js. Ryan Dahl created node.js in 2009. Then, created a better version called deno in 2018.
I recommend using Deno.