Sometimes you just want to run some JavaScript without bothering with an HTML file. That's what Node.js is for.
Installing Node.js
- Go to nodejs.org
- Download the version labeled LTS (that stands for "Long-Term Support," which is a fancy way of saying "the stable, reliable one")
- 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:
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.)
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:
node script.js
Output
> 2 + 2
4
> console.log("Hi from Node!")
Hi from Node!
undefinedSame 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 click | You 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.