How to Run JavaScript
There are few ways to run JavaScript code.
Embed 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.
Embed JavaScript file
<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.
Embed JavaScript code
in HTML file, include the following
<script> alert("hi!"); </script>
You should put this near the end of the HTML file, right above the close body
tag.
Embedding code like this is not recommended, unless the code is just few lines.
Execution Order of loading JavaScript code
Browser JavaScript Console
- A great way to learn JavaScript is to run it in browser's JavaScript console.
- Browser console is also essential for debugging JavaScript.
Using Deno
- Deno is a JavaScript runtime and compiler, runs in terminal.
- Most versatile, flexible, powerful, for developing JavaScript.
- It is for developing big project, including writing a server or desktop app.
Using node.js
- node.js is a JavaScript runtime and compiler, runs in terminal.
- Ryan Dahl created node.js in 2009.
- He created a better version called deno in 2018.
I recommend Deno.