How to Run JavaScript

By Xah Lee. Date: . Last updated: .

There are 3 major ways to run JavaScript code.

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's how to embed JavaScript into HTML. Put the following into a file:

<script>
alert("hi!");
</script>

For example, name the file test.html. Then, open it in a browser.

If you have more than a few lines of JavaScript code, you can put the JavaScript code in a dedicated file, like this:

<script src="test2.js"></script>
  1. Create a file named test2.html, with the above content.
  2. Create a file named test2.js, with the content alert("hi2");.
  3. Open the file test2.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

Another good way to test JavaScript code is Deno. With deno, you can run JavaScript like a shell script in terminal.

Download Deno at https://deno.land/

You can run it interactively. Type deno to start the interactive prompt. Type Ctrl+d to exit.

deno 2020-10-03 qfqxH
deno 2020-10-03

You can also run it as shell script.

For example, create a file named myscript.js, then put this in the content:

console.log (2+3);

Then, you can run the script in shell like this: deno run myscript.js .

Using Deno in Emacs

For emacs users, you can eval the JavaScript code in a buffer directly. See: Emacs: Run Current File

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.

Download Node.js at http://nodejs.org/

nodejs 2019-06-12 vt7xj
nodejs 2019-06-12
βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc