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>



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: JavaScript: How to Use Browser's JS 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. JavaScript: How to Use Browser's JS Console
  3. JavaScript Tutorial by Example
  4. JavaScript: Data Types
  5. JavaScript: true, false
  6. JavaScript: Operators
  7. JavaScript: Variable
  8. JavaScript: Branch Control: if then else, switch
  9. JavaScript: for while do Loop
  10. JavaScript: Array Basics
  11. JavaScript: Object Basics
  12. JavaScript: RegExp Tutorial
  13. JavaScript: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.