Running JavaScript with Node.js

Kindergarten, page 5 of 9. A two-minute read.

Sometimes you just want to run some JavaScript without bothering with an HTML file. That's what Node.js is for.

Installing Node.js

  1. Go to nodejs.org
  2. Download the version labeled LTS (that stands for "Long-Term Support," which is a fancy way of saying "the stable, reliable one")
  3. Install it with all the default options

To check it worked, open a terminal. In VS Code, the easiest way is to choose Terminal → New Terminal from the menu (or press Ctrl + `, the backtick key, usually just below Esc). A panel opens at the bottom of the window. Type this and press Enter:

Terminal
node --version

You should see a version number, something like v22.11.0. (Yours may be different. That's fine. As long as you see a number and not an error, you're good.)

Fun factWhat's a terminal?

The terminal (also called the command line, command prompt, or shell) is a way of controlling your computer by typing commands instead of clicking icons. It looks very "hacker in a movie," but it's actually pretty simple once you get used to it. We'll only use a handful of commands in this book.

Running a file

In your terminal, make sure you're inside your my-first-js folder (VS Code's terminal starts there automatically when you've opened the folder). Then type:

Terminal
node script.js

Output

> 2 + 2
4
> console.log("Hi from Node!")
Hi from Node!
undefined

Same output, no browser needed!

The Node playground

If you just type node on its own and press Enter, you get a playground just like the browser console:

(That undefined is just Node telling you that console.log doesn't give back an answer. You can ignore it for now. We'll understand it properly in Grade 6.) To leave the Node playground, type .exit or press Ctrl + C twice.

Browser or Node: which should I use?

Use the browser when...Use Node.js when...
You want to work with web pages, buttons, and things you can clickYou just want to practice pure JavaScript
You need alert, prompt, or the page itself (document)You're building a server or command-line tool

For Elementary and Middle School, almost every example works in both. In High School, when we start controlling web pages, you'll need the browser.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning