How to Run JavaScript

By Xah Lee. Date: . Last updated: .

There are 3 major ways to run JavaScript code.

Following are details of each.

Embedding JavaScript in HTML

To evaluate a piece of JavaScript code, you need to put JavaScript code in a HTML file and view the file in browser.

Here's how to embed JavaScript into HTML. Put the following into a file:


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 say to have “type” attribute like this:

<script type="text/javascript">…</script>


<script type="text/javascript" src="…"></script>

But the type attribute is not necessary since html5.

Use Browser's Web Developer Console

chrome js console 2016-10-27
Google Chrome browser web JavaScript console.

A good way to learn JavaScript is to run it in browser's JavaScript console.

See: JS: How to Use Browser Console.

Using node.js

Another good way to test JavaScript code is “node.js”. With node.js, you can run JavaScript like a shell script in terminal.

Download it at

On Linux, you can also install by sudo apt-get install nodejs, but that is usually much older version, as nodejs moves fast.

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

nodejs repl
node.js REPL

You can also run it as shell script.

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


Then, you can run the script in shell like this: node myscript.js. (For emacs users, you can eval the JavaScript code in a buffer directly. See: Emacs Lisp: a Command to Execute/Compile Current File)

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Tutorial by Example
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth