How to Run JavaScript: Browser Console, Node.js REPL, Files and Web Pages

Before you learn the language itself, you need a quick, reliable way to run code and see the result. JavaScript can run in five places: the browser console, the Node.js REPL, a .js file, a one-line terminal command and a web page. In this lesson you will use all five, learn when to pick each one, and fix the errors beginners hit most often, such as document is not defined.

Advertisement

📖 What You’ll Learn: the browser DevTools console, the Node.js REPL and its commands, running .js files with arguments, node -e and node -p, adding JavaScript to a web page, checking syntax with node –check, running and debugging in VS Code, and the difference between browser and Node.js code.


🗺️ Five Ways to Run JavaScript

WhereHowBest for
Browser consoleF12 › ConsoleTrying one line, inspecting a web page
Node.js REPLType node in a terminalExperimenting with language features
A .js filenode app.jsReal programs, practice questions, tests
One-line commandnode -p "..."Quick calculations in scripts and CI
A web page<script src="app.js">Code that changes a page (DOM)

In this course you will mostly run files with Node.js, because a file can be saved, edited, re-run and tested.


🖥️ Run JavaScript in the Browser Console

Definition: the console is part of the browser’s Developer Tools (DevTools). It runs any JavaScript you type, in the context of the page that is open.

  1. Open any web page, for example https://example.com.
  2. Press F12 (or Ctrl+Shift+J on Windows/Linux, Cmd+Option+J on macOS) and select the Console tab.
  3. Type an expression after the > prompt and press Enter.

⌨️ Typed in the console (one line at a time)

2 + 3
"sqatools".toUpperCase()
[1, 2, 3].map(n => n * 10)
document.title

🖥️ Output (Chrome console on example.com)

5
'SQATOOLS'
(3) [10, 20, 30]
'Example Domain'
  • The console prints the value of each expression automatically; you do not need console.log here.
  • document.title works because the console runs inside the page, where the document object exists.
  • Press Shift+Enter to write several lines before running them.

⚠️ Watch out: The first time you paste code into the Chrome console, Chrome blocks it and asks you to type allow pasting. This protects you from scams that ask people to paste code that steals their account. Only paste code you understand.


🔁 The Node.js REPL

Definition: a REPL (Read-Eval-Print Loop) reads one line, evaluates it, prints the result and waits for the next line. Start it by typing node with no file name.

⌨️ Terminal

node

🖥️ Output (REPL session)

Welcome to Node.js v26.13.0.
Type ".help" for more information.
> 2 + 3
5
> const name = "Asha"
undefined
> `Hi ${name}`
'Hi Asha'
> [1, 2, 3].map(n => n * 2)
[ 2, 4, 6 ]
> Math.max(4, 9, 2)
9
> _
9
> .exit
  • A declaration such as const name = ... prints undefined because a declaration has no value. This is normal.
  • _ (underscore) holds the result of the last expression.
  • Press Tab to autocomplete: type Math. and press Tab twice to list every Math method.
REPL commandWhat it does
.helpLists all REPL commands
.editorMulti-line editor mode; finish with Ctrl+D
.load file.jsRuns a file inside the current session
.save file.jsSaves everything you typed to a file
.exit or Ctrl+C twiceLeaves the REPL

Advertisement

📄 Run a JavaScript File with Node.js

For anything longer than a line, save the code in a file with the .js extension and run node <file> from the folder that contains it.

📄 greet.js

const name = process.argv[2] || "tester";
const hour = 9;

const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(`${greeting}, ${name}!`);

⌨️ Terminal

node greet.js

🖥️ Output

Good morning, tester!

process.argv is an array of the command-line arguments. Items 0 and 1 are the paths of node and the file, so your first own argument is process.argv[2]:

📄 greet.js

const name = process.argv[2] || "tester";
const hour = 9;

const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(`${greeting}, ${name}!`);

⌨️ Terminal

node greet.js Asha

🖥️ Output

Good morning, Asha!
  • || "tester" provides a default value when no argument is given.
  • The ? : (conditional operator) picks one of two strings. You will learn it in the Operators lesson.
  • Run files from the right folder: node greet.js only works if the terminal is in the folder that contains greet.js.

💡 Tip: Use node --watch greet.js while you practise. Node.js reruns the file every time you save it.


⚡ One-Line Commands: node -e and node -p

node -e (“evaluate”) runs a string of code. node -p (“print”) runs it and prints the result. Both are handy in scripts and CI pipelines.

⌨️ Terminal

node -e "console.log('Sum:', 2 + 3)"
node -p "40 + 2"
node -p "'sqatools'.toUpperCase()"

🖥️ Output

Sum: 5
42
SQATOOLS

⚠️ Watch out: Quoting differs between shells. On Windows Command Prompt use double quotes outside and single quotes inside, as shown. In PowerShell, bash and zsh, single quotes outside (node -p '40 + 2') also work.


🌍 Run JavaScript in a Web Page

Browsers run JavaScript that a page loads with the <script> tag. Create two files in the same folder:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My first script</title>
</head>
<body>
  <h1 id="title">Hello</h1>
  <button id="btn">Click me</button>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

const title = document.getElementById("title");
const button = document.getElementById("btn");

button.addEventListener("click", () => {
  title.textContent = "JavaScript is running!";
  console.log("Button clicked at", new Date().toLocaleTimeString());
});

Double-click index.html to open it, click the button, and the heading changes. Open the console (F12) to see the log line. In VS Code, the free Live Server extension reloads the page automatically when you save.

  • Put the <script> tag at the end of <body> (or use <script src="app.js" defer> in the head) so the HTML elements exist before the script looks for them.
  • document and addEventListener are browser APIs. Module 12 of this course covers the DOM in detail.

Advertisement

🚫 Browser Code in Node.js: “document is not defined”

The JavaScript language is the same everywhere, but the browser and Node.js provide different global objects. Running browser code with Node.js fails:

📄 page.js

const title = document.getElementById("title");
console.log(title);

⌨️ Terminal

node page.js

🖥️ Output

/home/you/js-course/page.js:1
const title = document.getElementById("title");
              ^

ReferenceError: document is not defined
    at Object.<anonymous> (/home/you/js-course/page.js:1:15)

Node.js v26.13.0

Fix: run DOM code in a browser (a web page or the console). For tests, tools such as Playwright drive a real browser for you. The reverse also happens: process, require and fs do not exist in the browser.

Available inExamples
Bothconsole, Math, JSON, setTimeout, fetch, URL, structuredClone
Browser onlywindow, document, localStorage, alert
Node.js onlyprocess, require, __dirname (CommonJS), modules such as fs and path

A script can check where it is running and behave accordingly:

📄 where.js

const where = typeof window === "undefined" ? "Node.js" : "a browser";
console.log(`This code is running in ${where}.`);
console.log("fetch available?", typeof fetch === "function");

⌨️ Terminal

node where.js

🖥️ Output

This code is running in Node.js.
fetch available? true

🔍 Check Syntax Without Running: node –check

node --check parses a file and reports syntax errors without executing it. This is useful in CI or before running a script that changes data.

📄 bad.js

console.log("missing paren"

⌨️ Terminal

node --check bad.js

🖥️ Output

/home/you/js-course/bad.js:1
console.log("missing paren"
            ^^^^^^^^^^^^^^^

SyntaxError: missing ) after argument list

Node.js v26.13.0

The caret (^^^^) points at the problem and the message says what is missing. Add the closing ) and node --check bad.js prints nothing, which means the syntax is valid.


🧑‍💻 Run and Debug in VS Code

  1. Open the built-in terminal (Ctrl+`) and type node greet.js. This is the method used throughout the course.
  2. Or open the file and press F5, then choose Node.js. VS Code runs the file with its debugger attached and shows output in the Debug Console.
  3. Click in the gutter left of a line number to set a red breakpoint. When you press F5, the program pauses there and you can hover over variables to see their values.

You will use breakpoints properly in the Console Methods and Debugging Basics lesson.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Open the browser console on any page and print the page title and the page URL. Which two expressions do you type?

Show answer

document.title and location.href (or window.location.href). The console prints both values without console.log.

Q2. In the Node.js REPL, type 10 * 3 and then use the last result to add 5. What do you type the second time?

Show answer

Type _ + 5. The underscore holds the last result (30), so the REPL prints 35.

Q3. Write square.js that reads a number from the command line and prints its square. node square.js 7 should print 7 squared is 49.

Show answer

📄 square.js

const n = Number(process.argv[2] || 7);
console.log(`${n} squared is ${n * n}`);

🖥️ Output

7 squared is 49

Command-line arguments are strings, so Number() converts "7" to 7. The default 7 keeps the example working with no argument.

Q4. Use a one-line command to print the current year without creating a file.

Show answer
node -p "new Date().getFullYear()"

Q5. A learner runs node app.js and gets ReferenceError: document is not defined. Explain why and give two ways to fix it.

Show answer

document is a browser object; Node.js has no web page, so the name does not exist. Fix 1: load the script in an HTML page with <script src="app.js"> and open it in a browser. Fix 2: if the code does not need the page, remove the DOM code. For automated browser checks, use a tool such as Playwright.

Q6. Write a script that prints Running in Node.js or Running in a browser depending on where it runs.

Show answer

📄 env.js

if (typeof window === "undefined") {
  console.log("Running in Node.js");
} else {
  console.log("Running in a browser");
}

🖥️ Output

Running in Node.js

typeof on an undeclared name returns "undefined" instead of throwing an error, so this check is safe in both places.


🧠 MCQ Quiz: Run JavaScript: Console, REPL, Files

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does REPL stand for?
  2. How do you start the Node.js REPL?
  3. In the REPL, what does _ contain?
  4. Which command prints the result of an expression?
  5. With node greet.js Asha, where is "Asha"?
  6. Why does node app.js fail with document is not defined?
  7. What does node --check file.js do?
  8. Where should a <script> tag that changes page elements usually go?
  9. Which of these exists in both the browser and Node.js?
  10. Why does Chrome ask you to type allow pasting in the console?

💼 Interview Questions and Answers

Q1. What is the difference between running JavaScript in the browser and in Node.js?

The language (ECMAScript) is the same, but the host APIs differ. Browsers provide the DOM (document), window, storage and rendering, and run code in a sandbox. Node.js provides file system, network servers, process and the module system, with no DOM. Code that uses only language features and shared APIs (fetch, timers, URL) runs in both.

Q2. How do you pass input to a Node.js script, for example test data or an environment name?

  • Command-line arguments: process.argv, or util.parseArgs() for named flags such as --env=qa.
  • Environment variables: process.env.BASE_URL, often loaded from a .env file with node --env-file=.env.
  • Files: read JSON or CSV test data with fs.

Q3. A script works when you run it from its folder but fails in CI with “Cannot find module”. What is the likely cause?

Paths are resolved from the current working directory. CI may run the command from the repository root, so node app.js or a relative file path points to the wrong place. Fix it by running from the right folder (working-directory in GitHub Actions), using an npm script, or building paths from the script location (__dirname or import.meta.dirname).

Q4. What is the purpose of defer on a script tag?

<script defer src="app.js"> downloads the script in parallel while the HTML is parsed, then runs it after parsing has finished and in document order. The script can safely access all elements, and the page is not blocked while the file downloads.


Advertisement

❓ Frequently Asked Questions

🤔 What is the easiest way to run JavaScript?

Open your browser, press F12, choose Console and type code. For anything longer than a line, save a .js file and run it with node file.js.

🤔 Can I run JavaScript without installing anything?

Yes. Every browser runs JavaScript in its console and in web pages. You need Node.js only to run files from the terminal.

🤔 Why does the REPL print undefined after my line?

Statements such as const x = 5 or a console.log() call do not produce a value, so the REPL prints undefined. Your code still ran.

🤔 How do I run a JavaScript file in VS Code?

Open the terminal with Ctrl+` and type node yourfile.js, or press F5 and choose Node.js to run it with the debugger.


🏁 Summary

  • Use the browser console for quick checks on a page, the Node.js REPL for experiments, and .js files for real programs.
  • node file.js runs a file; process.argv holds command-line arguments.
  • node -p prints an expression’s result; node -e runs code; node --check validates syntax.
  • Web pages load JavaScript with <script src> at the end of the body or with defer.
  • Browser APIs such as document do not exist in Node.js, and Node.js APIs such as process do not exist in the browser.

Next, continue with Lesson 4: Syntax, Comments and Strict Mode.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in