Setting Up and Running Code
Objectives
By the end of this chapter, you should be able to:
- Run JavaScript in your browser’s console
- Install Node.js and run a script from a file
- Write and run your first JavaScript program
💡 Why this matters: Every lesson in this course asks you to run code. You need a place to actually do that first.
Quickest Option: The Browser Console
Every browser has a JavaScript console built in, and it’s the fastest way to try a line of code with zero setup.
- Open your browser.
- Open Developer Tools: right-click anywhere on a page and choose Inspect, or press
F12(Windows/Linux) orCmd+Option+I(Mac). - Click the Console tab.
- Type a line of JavaScript and press Enter:
2 + 2
You should see 4 printed back. The console is great for quick one-off checks, which is exactly what you’ll use it for in this lesson and the next.
Running a Script from a File: Node.js
The console works line by line, but real programs live in files. For that, install Node.js, which lets you run a .js file directly from your terminal.
- Download Node.js from nodejs.org (choose the LTS version).
- Confirm the install by running this in your terminal:
node --version
- Create a file called
first.jswith one line:
console.log("Hello, JavaScript");
- Run it:
node first.js
# Hello, JavaScript
console.log() prints a value. You’ll use it constantly to check what your code is actually doing.
Two Ways to Run Code
Like most languages, Node gives you both a REPL and a script runner.
The REPL (type node with nothing after it) is an interactive prompt, similar to the browser console: type a line, see the result immediately.
node
> 2 + 2
4
> .exit
A script is a .js file holding your whole program, run with node filename.js. This is how the rest of this course expects you to work: write code in a file, then run the file.
Try It
- Open your browser console and run
10 * 4. - Install Node.js and confirm it with
node --version. - Create
first.jswithconsole.log("Hello, JavaScript")and run it withnode first.js.
Recap
- The browser console is the fastest way to try a single line of JavaScript.
- Node.js runs JavaScript files from your terminal with
node filename.js. console.log()prints a value so you can see what your code is doing.
Next lesson: variables, data types, and the operators you’ll use to work with them.