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:

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

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

or

<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 http://nodejs.org/.

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:

console.log(2+3);

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. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog