How to Run JavaScript in the Browser and Node
Learn how to run JavaScript code in both browser environments and Node.js. This guide covers the browser console, HTML script tags, Node.js REPL, and file execution with practical examples for each approach.
One of the biggest advantages of learning JavaScript is that you can run it almost anywhere. Unlike languages that require a compiler installation and a complex build setup, JavaScript runs natively in every web browser on your computer and, with Node.js installed, directly from your terminal. This flexibility makes it the fastest language to go from "I want to try coding" to "my code is running."
This guide covers every practical way to execute JavaScript, from the quickest (opening your browser's console) to the most production-ready (running files with Node.js). By the end, you will know exactly which method to use for different situations.
Running JavaScript in the Browser
Every modern web browser ships with a built-in JavaScript engine that can execute code instantly. You do not need to install anything.
Method 1: The Browser Console
The fastest way to run JavaScript is through the browser's built-in developer console. It is a REPL (Read-Eval-Print Loop) that executes code one line at a time and immediately shows the result.
// Open the console (F12 or Ctrl+Shift+J in Chrome)
// Type this and press Enter:
console.log("Hello from the browser console!");
// Output: Hello from the browser console!
// Try arithmetic:
25 * 4 + 10
// Output: 110
// Create variables and use them:
const name = "RuneHub";
console.log(`Welcome to ${name}`);
// Output: Welcome to RuneHub| Browser | Shortcut to Open Console | Menu Path |
|---|---|---|
| Chrome | Ctrl+Shift+J (Windows) / Cmd+Option+J (Mac) | More Tools > Developer Tools > Console |
| Firefox | Ctrl+Shift+K (Windows) / Cmd+Option+K (Mac) | Web Developer > Web Console |
| Edge | Ctrl+Shift+J | More Tools > Developer Tools > Console |
| Safari | Cmd+Option+C | Develop > Show JavaScript Console |
When to Use the Console
The browser console is perfect for quick experiments, testing code snippets, and debugging. It is not the right place to write full applications, but it is the fastest way to test an idea.
Method 2: JavaScript in an HTML File
For anything beyond quick experiments, you write JavaScript inside or alongside an HTML file. There are two approaches: inline scripts and external script files.
Inline script (embedded directly in HTML):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline JavaScript Demo</title>
</head>
<body>
<h1 id="greeting">Loading...</h1>
<script>
const hour = new Date().getHours();
let message;
if (hour < 12) {
message = "Good morning!";
} else if (hour < 18) {
message = "Good afternoon!";
} else {
message = "Good evening!";
}
document.getElementById("greeting").textContent = message;
</script>
</body>
</html>External script file (recommended for real projects):
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External Script Demo</title>
<script src="app.js" defer></script>
</head>
<body>
<h1 id="greeting">Loading...</h1>
<p id="temperature"></p>
</body>
</html>// app.js (separate file in the same folder)
const hour = new Date().getHours();
let message;
if (hour < 12) {
message = "Good morning!";
} else if (hour < 18) {
message = "Good afternoon!";
} else {
message = "Good evening!";
}
document.getElementById("greeting").textContent = message;
// Simulate a temperature reading
const temperature = Math.round(Math.random() * 15 + 15);
document.getElementById("temperature").textContent =
`Current temperature: ${temperature}°C`;To run this, save both files in the same folder and double-click index.html to open it in your browser. The browser loads the HTML, downloads app.js, and executes it.
Method 3: Live Server (Recommended for Development)
Double-clicking an HTML file works, but it opens with the file:// protocol, which has limitations (no network requests, some APIs disabled). For real development, use a local HTTP server.
# If you have Node.js installed, use npx to run a quick server:
npx serve .
# Or install the VS Code "Live Server" extension,
# right-click your HTML file, and select "Open with Live Server"
# Your page opens at http://localhost:3000 (or similar)
# Changes to your files auto-refresh the browserRunning JavaScript with Node.js
Node.js is a runtime that lets you execute JavaScript outside the browser. It embeds Google's V8 engine and adds APIs for file system access, networking, and operating system interactions that browsers do not provide.
Installing Node.js
Download the LTS (Long Term Support) version from nodejs.org. After installation, verify it works:
# Check Node.js version
node --version
# Output: v22.x.x (or similar)
# Check npm (Node Package Manager) version
npm --version
# Output: 10.x.x (or similar)Method 4: The Node.js REPL
Just like the browser console, Node.js has its own interactive REPL. Open your terminal and type node:
$ node
Welcome to Node.js v22.x.x.
Type ".help" for more information.
> 2 + 2
4
> const fruits = ["apple", "banana", "cherry"]
undefined
> fruits.map(f => f.toUpperCase())
[ 'APPLE', 'BANANA', 'CHERRY' ]
> .exitThe Node.js REPL is useful for testing algorithms, exploring APIs, and quick prototyping. Type .help to see available commands like .save (save session to file) and .load (load a file into the session).
Method 5: Running JavaScript Files with Node
For real projects, you write .js files and execute them from the terminal:
// calculator.js
function calculateTip(billAmount, tipPercent, partySize) {
const tipAmount = billAmount * (tipPercent / 100);
const total = billAmount + tipAmount;
const perPerson = total / partySize;
return {
tipAmount: tipAmount.toFixed(2),
total: total.toFixed(2),
perPerson: perPerson.toFixed(2)
};
}
const result = calculateTip(85.50, 18, 4);
console.log("Tip Calculator Results:");
console.log(` Bill: $85.50`);
console.log(` Tip (18%): $${result.tipAmount}`);
console.log(` Total: $${result.total}`);
console.log(` Per person (4 people): $${result.perPerson}`);# Run the file from your terminal
node calculator.js
# Output:
# Tip Calculator Results:
# Bill: $85.50
# Tip (18%): $15.39
# Total: $100.89
# Per person (4 people): $25.22Key Differences Between Browser and Node.js
While both environments run JavaScript using the same language specification (ECMAScript), they provide very different APIs.
| Feature | Browser | Node.js |
|---|---|---|
| JavaScript Engine | V8 (Chrome/Edge), SpiderMonkey (Firefox), JSC (Safari) | V8 |
| DOM Access | Yes (document, window) | No |
| File System | No (sandboxed) | Yes (fs module) |
| Network Requests | fetch, XMLHttpRequest | fetch (built-in since v18), http module |
| Global Object | window | global (or globalThis for both) |
| Module System | ES Modules (import/export) | CommonJS (require) + ES Modules |
| Package Manager | None (use CDN or bundler) | npm, yarn, pnpm |
| Use Case | Interactive web pages, SPAs | Servers, CLIs, scripts, APIs |
// This works in BOTH browser and Node.js:
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(`Sum: ${sum}`); // Sum: 150
// This works ONLY in the browser:
// document.getElementById("output").textContent = sum;
// This works ONLY in Node.js:
// const fs = require("fs");
// fs.writeFileSync("result.txt", `Sum: ${sum}`);DOM is Browser-Only
If you try to use document or window in Node.js, you will get a [ReferenceError](/tutorials/programming-languages/javascript/basic-javascript-debugging-tips-for-beginners): document is not defined. Node.js does not have a DOM because there is no HTML page to represent. Similarly, Node.js modules like fs and path are not available in browser JavaScript.
Choosing the Right Execution Method
| Situation | Best Method | Why |
|---|---|---|
| Quick test or experiment | Browser console | Zero setup, instant feedback |
| Learning JavaScript basics | Node.js REPL or browser console | Interactive, shows results immediately |
| Building a web page | HTML file + external .js + Live Server | Full DOM access, auto-refresh on changes |
| Building a CLI tool or script | Node.js file execution (node script.js) | File system access, npm packages |
| Building a server or API | Node.js with Express/Fastify | Network APIs, database drivers |
| Running automated tests | Node.js with test runner | Jest, Vitest, or built-in node --test |
Best Practices
Start with the browser console for new concepts. When learning a new JavaScript feature, the browser console gives you instant feedback without creating files. Type the expression, see the result, iterate.
Use external script files for anything beyond 10 lines. Inline <script> blocks are fine for tiny demos, but they mix concerns (HTML structure + application logic) and cannot be cached by the browser. Separate .js files are easier to maintain and get cached.
Always add defer to script tags in the head. When linking external JavaScript files from the <head> section, the defer attribute ensures the script downloads in parallel with HTML parsing and executes after the DOM is ready.
Use "use strict" at the top of Node.js files. Strict mode catches common mistakes like undeclared variables and silent assignment failures. In ES modules and type="module" scripts, strict mode is automatic.
Keep Node.js updated to the latest LTS version. Each new LTS release brings performance improvements, security patches, and new JavaScript features. Check your version with node --version and update from nodejs.org.
Common Mistakes and How to Avoid Them
Beginners Frequently Hit These Issues
These mistakes are easy to make when you are first learning to run JavaScript in different environments.
Trying to access the DOM in Node.js. Writing document.querySelector("h1") in a Node.js file produces ReferenceError: document is not defined. If you need to manipulate HTML server-side, use libraries like jsdom or cheerio.
Forgetting to save the file before running node filename.js. Your terminal runs whatever is saved on disk, not what is displayed in your editor. If changes are not reflected, check that you saved with Ctrl+S.
Using require() in the browser. The CommonJS require() function is a Node.js feature. Browsers use <script> tags or ES modules (import/export). If you want to use npm packages in the browser, use a bundler like Vite, Webpack, or esbuild.
Opening HTML files directly instead of using a local server. The file:// protocol blocks fetch() calls, disables some security APIs, and does not set correct MIME types. Always use a local development server for real work.
Next Steps
Master the Chrome DevTools console
Learn the full power of Chrome DevTools for running code, inspecting elements, and debugging JavaScript in real time.
Learn JavaScript variables
Now that you can run code, start writing real programs by learning how to declare and use variables with let, const, and how to store different types of data.
Build your first project
Combine HTML and JavaScript to build a simple interactive project like a temperature converter or a tip calculator. Running code in a project context solidifies your understanding.
Explore Node.js for backend development
If server-side JavaScript interests you, learn how to build a basic HTTP server with Node.js and handle incoming requests.
Rune AI
Key Insights
- Browser console for experiments: The fastest way to test JavaScript with zero setup; just press F12 and start typing
- External script files for real projects: Always separate JavaScript into
.jsfiles with thedeferattribute for better caching and maintainability - Node.js for server-side work: Install Node.js to run JavaScript outside the browser with access to file system, networking, and npm packages
- Same language, different APIs: Core JavaScript is identical across environments; the differences are in the APIs each runtime provides (DOM vs. file system)
- Use a local server for development: Avoid the
file://protocol; use Live Server ornpx servefor proper HTTP behavior during development
Frequently Asked Questions
Do I need to install anything to run JavaScript in the browser?
Is Node.js required to learn JavaScript?
Can I use the same JavaScript code in both the browser and Node.js?
What is the difference between the browser console and the Node.js REPL?
Should I learn JavaScript in the browser or Node.js first?
Conclusion
JavaScript's ability to run in both browsers and Node.js makes it uniquely versatile among programming languages. The browser gives you instant access through the console and DOM manipulation through HTML files, while Node.js opens up server-side programming, file system access, and the npm ecosystem. Knowing which environment to use for which task, and understanding the differences between them, is a foundational skill that every JavaScript developer needs.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.