Computer Programming 1 (JavaScript) • Environment, Syntax & Types

Running JavaScript (Browser vs. Node) — I can run JavaScript in the browser console and in a file (script tag or Node) and explain the difference at a high level.

Discover the two main places JavaScript runs and why that matters for everything you build.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

In the early 1990s, web pages were completely static—just text and images with no interactivity at all. If you clicked a button, the page had to reload entirely from the server before anything could change. Developers wanted a way to make web pages respond instantly to user actions, and that need gave birth to JavaScript. Originally, JavaScript could only run inside a web browser, but today it also runs on servers and desktops thanks to a tool called Node.js. Understanding where your code runs is one of the first skills every JavaScript programmer needs.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in just 10 days at Netscape. It runs exclusively inside the Netscape Navigator browser, adding interactivity to web pages for the first time.

2004 • AJAX & Gmail Change the Web

Google launches Gmail using AJAX (Asynchronous JavaScript and XML), proving that browser-based JavaScript can power complex, app-like experiences without full page reloads.

2008 • Chrome's V8 Engine

Google releases the Chrome browser with its V8 JavaScript engine, dramatically increasing execution speed and proving JavaScript can handle serious workloads.

2009 • Node.js Breaks Free

Ryan Dahl takes the V8 engine out of Chrome and wraps it in a standalone runtime called Node.js, allowing JavaScript to run on servers, desktops, and anywhere outside a browser.

2024 • JavaScript Everywhere

JavaScript is the most widely used programming language in the world, running in billions of browsers and powering millions of server applications through Node.js and newer runtimes like Deno and Bun.

This history raises a key question: if the same language can run in a browser and also on a server through Node.js, what's actually different about those two environments? That's exactly what this lesson explores.

SECTION 2

Core Principles & Definitions

Before diving into hands-on examples, you need to understand a few foundational ideas. A runtime environment is the place where your code actually executes—think of it as the "stage" where your program performs. JavaScript has two main stages: the browser and Node.js. Each stage provides different tools and capabilities, even though the core language (variables, loops, functions) stays the same.

1

JavaScript Engine

The core software that reads and executes JavaScript code. Chrome uses V8, Firefox uses SpiderMonkey. Node.js also uses V8 under the hood.
2

Browser Environment

When JavaScript runs in a browser, it gains access to the DOM (Document Object Model), which lets you change HTML elements, respond to clicks, and display alerts on screen.
3

Node.js Environment

When JavaScript runs in Node.js, it can access the file system, create web servers, and interact with databases—things browsers cannot do for security reasons.
4

The Console

Both environments provide a console for testing quick code snippets and printing output with console.log(). It's your most important debugging tool.
✦

KEY TAKEAWAY

Think of the JavaScript language as a universal set of cooking skills (chopping, sautéing, seasoning). The browser is like a kitchen in a restaurant—you can plate food and serve it to customers (display web pages to users). Node.js is like a kitchen in a warehouse—you can store ingredients, manage inventory, and prepare bulk orders (handle files, databases, and servers). Same cooking skills, different kitchens, different tools on the counter.

SECTION 3

Visual Explanation — Two Environments, One Language

JavaScript Runtime EnvironmentsCORE JAVASCRIPTVariables · Functions · Loops · Objects · Arrays · Strings🌐 BROWSERdocument (DOM)window / alert() / prompt()fetch() for HTTP requestsconsole (DevTools)Runs via <script> tag or console⚙️ NODE.JSfs (file system)http / https (create servers)process / os (system info)console (terminal)Runs via: node myFile.js
The yellow dashed box at the top represents the core JavaScript language shared by both environments. The blue box on the left shows what the browser adds (DOM, window, alert). The green box on the right shows what Node.js adds (file system, HTTP servers, process info). Notice that console.log() exists in both environments—it just outputs to different places.

As you can see in the diagram above, the core of JavaScript—things like declaring variables with let, writing if statements, and creating functions—is identical in both environments. The differences come from the extra tools each environment provides. A browser gives you access to the web page itself through the DOM, while Node.js gives you access to the computer's file system and networking capabilities. This distinction is crucial because it determines what your code can actually do.

SECTION 4

How It Works — Running Code in Each Environment

Method 1: The Browser Console

Every modern browser (Chrome, Firefox, Edge, Safari) has a built-in developer console where you can type JavaScript and see results instantly. To open it in Chrome, press Ctrl + Shift + J on Windows/Linux or Cmd + Option + J on Mac. You'll see a blinking cursor where you can type code like console.log("Hello, world!"); and press Enter to run it. This is the fastest way to experiment with JavaScript, and it's perfect for testing small snippets.

Method 2: The <script> Tag in an HTML File

For anything more than a quick experiment, you write JavaScript inside an HTML file using script tags. You can place code directly between <script> and </script> tags, or you can link to a separate .js file using <script src="app.js"></script>. When a browser loads your HTML file, it reads the script tag and executes the JavaScript code. This is how real websites add interactivity—form validation, animations, dynamic content, and much more.

Method 3: Node.js in the Terminal

With Node.js installed on your computer, you can run JavaScript files directly from the terminal (also called the command line). You create a file like app.js, write your code in it, and then run it by typing node app.js in the terminal. No browser needed, no HTML file needed. You can also type node by itself to open an interactive console (called a REPL, which stands for Read-Eval-Print Loop) that works similarly to the browser console.

Three Ways to Run JavaScript1. Browser Console>2 + 24>console.log("Hi")Open withCtrl+Shift+JQuick experiments✓ Instant feedback✓ No setup needed✗ Code not saved2. Script Tag (HTML)<!DOCTYPE html><html> <body> <script> alert("Hi!"); </script>Open HTML in browserReal web pages✓ Code is saved in file✓ Interacts with HTML✓ Can use DOM3. Node.js (Terminal)$node app.jsHello from Node!$Run in terminal withnode filename.jsServers & tools✓ Access to file system✓ No browser needed✗ No DOM access
This diagram shows the three main methods for running JavaScript. The browser console is great for quick tests, the script tag is how you build real web pages, and Node.js lets you run JavaScript outside the browser entirely.

SECTION 5

Key Differences Between Browser and Node.js

Now that you know the three ways to run JavaScript, let's dig deeper into exactly how the browser and Node.js environments differ. These differences are not about the language itself—they're about the APIs (Application Programming Interfaces), which are the extra tools each environment makes available. An API is simply a set of built-in functions and objects that you can use in your code.

FeatureBrowserNode.js
Global Objectwindowglobal (or globalThis)
DOM AccessYes — document.getElementById()No — no HTML to interact with
User Interactionalert(), prompt(), click eventsTerminal input via readline module
File SystemNo — blocked for securityYes — fs.readFile(), fs.writeFile()
HTTP ServerNo — browsers make requests, not serve themYes — http.createServer()
Module Systemimport via ES modulesrequire() (CommonJS) or import
console.log() OutputDevTools Console panelTerminal / Command Prompt

Side-by-side comparison of browser and Node.js environments

ℹ

Why Can't Browsers Access Files?

Imagine if any website you visited could read files on your computer—your photos, documents, passwords. That would be a massive security risk. Browsers deliberately sandbox JavaScript, meaning they restrict it to only interact with the web page and the server it came from. Node.js doesn't need this restriction because you are choosing to run the code on your own machine.

SECTION 6

Worked Example — Running the Same Code Both Ways

Let's walk through a concrete example of writing JavaScript code and running it in both the browser and Node.js. We'll build a simple program that calculates the area of a rectangle and outputs the result.

Calculate Rectangle Area in Browser and Node.js

  1. 1

    Step 1 — Write the Core JavaScript

    Create a file called area.js and write the following code. This code works in both environments because it uses only core JavaScript features: let width = 8; let height = 5; let area = width * height; console.log("The area is: " + area);
    Output: The area is: 40
  2. 2

    Step 2 — Run It in the Browser Console

    Open Chrome and press Ctrl+Shift+J (or Cmd+Option+J on Mac). Paste all four lines into the console and press Enter. You'll see The area is: 40 printed in the console panel inside the browser window.
    Output appears in the DevTools Console panel
  3. 3

    Step 3 — Run It with Node.js

    Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux). Navigate to the folder where you saved area.js and type node area.js. You'll see the exact same output, but this time it appears directly in the terminal—no browser involved.
    Output appears in the terminal window
  4. 4

    Step 4 — Run It in an HTML File (Script Tag)

    Create a file called index.html with this content: <!DOCTYPE html> <html><body> <h1>Area Calculator</h1> <script src="area.js"></script> </body></html> Open this HTML file in your browser. The heading "Area Calculator" appears on the page, and the output from area.js shows up in the DevTools console.
    The same .js file can be loaded by an HTML page or run directly with Node.js.
  5. 5

    Step 5 — Try Something Environment-Specific

    Now try adding alert("Area is " + area); to area.js. In the browser, you'll see a popup box. In Node.js, you'll get an error: ReferenceError: alert is not defined. This proves that alert() is a browser-only feature, not part of core JavaScript.
    Environment-specific APIs cause errors when used in the wrong environment.

SECTION 7

Strengths & Limitations of Each Environment

Neither the browser nor Node.js is "better" than the other—they're designed for different jobs. Choosing the right environment depends entirely on what you're trying to build. Here's a comparison of what each environment excels at and where it falls short.

CriteriaBrowserNode.js
Best ForInteractive web pages, animations, forms, games that run in a web browserWeb servers, command-line tools, scripts that process files, backend APIs
Setup RequiredNone — every computer already has a browserMust download and install Node.js from nodejs.org
SecuritySandboxed — can't access local files or system resourcesFull access — can read/write files and connect to databases
Visual OutputRich — can manipulate the entire visible web pageText only — outputs to the terminal
Package EcosystemCDN-hosted libraries via script tagsnpm — the world's largest software registry with over 2 million packages

Strengths and limitations of each JavaScript runtime environment

✦

KEY TAKEAWAY

Think of it this way: the browser is like the front desk of a hotel—it's what guests (users) see and interact with. Node.js is like the back office—it handles reservations, accounting, and inventory that guests never see directly. Most real-world web applications use both: browser JavaScript for the user interface and Node.js for the server that stores and processes data.

SECTION 8

Connection to Full-Stack Development

Understanding the difference between browser and Node.js environments is your first step toward full-stack development—the practice of building both the front end (what users see in the browser) and the back end (the server that handles data and logic). JavaScript is unique among programming languages because it can power both sides. Before Node.js existed, developers typically had to learn separate languages for front end (JavaScript) and back end (Python, Ruby, PHP, or Java).

ConceptWhat You Know NowWhat Comes Next
Running CodeBrowser console, script tags, node file.jsBuild tools (Webpack, Vite) that bundle code automatically
Browser APIsdocument, alert(), console.log()DOM manipulation, event listeners, fetch() for API calls
Node.js APIsfs, http (conceptually)Express.js framework, database connections, REST APIs
Alternative RuntimesBrowser and Node.jsDeno (created by Node's original author) and Bun (ultra-fast runtime)

From beginner concepts to advanced full-stack development

As you progress through this course, you'll start with the browser environment because it's the easiest to set up and provides instant visual feedback. Later, you may explore Node.js to build command-line tools or simple servers. The important thing right now is that you understand the distinction: same language, different capabilities, different use cases.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words what a "runtime environment" is. Why does it matter whether JavaScript runs in a browser or in Node.js if the core language is the same?
Show answer
A runtime environment is the place where your code actually executes—it provides the engine that reads your JavaScript plus a set of extra tools (APIs) your code can use. Even though the core language (variables, functions, loops) is the same, the environment determines what additional capabilities are available. The browser provides APIs for interacting with web pages (the DOM, alert boxes, CSS manipulation), while Node.js provides APIs for interacting with the computer (reading files, creating servers). This matters because code that uses browser-specific features like document.getElementById() will not work in Node.js, and code that uses Node-specific features like fs.readFile() will not work in the browser.

Question 2: BASIC CALCULATION

Write a short JavaScript program (3–4 lines) that creates two variables, price and quantity, multiplies them to get a total, and logs the result using console.log(). Then state whether this code would work in (a) the browser console, (b) a script tag, and (c) Node.js.
Show answer
Here is the program: let price = 12.99; let quantity = 3; let total = price * quantity; console.log("Total: $" + total); This code would work in all three environments—(a) browser console, (b) script tag, and (c) Node.js—because it uses only core JavaScript features: variable declarations, multiplication, string concatenation, and console.log(). None of these are environment-specific. The output would be Total: $38.97 in all three cases, though it would appear in different places (DevTools panel vs. terminal).

Question 3: INTERMEDIATE

A student writes the following code in a file called greeting.js: let name = prompt("What is your name?"); console.log("Hello, " + name + "!"); They run it with node greeting.js and get an error. Explain why the error occurs, what the error message would likely say, and describe how to fix the code so it works in Node.js.
Show answer
The error occurs because prompt() is a browser-only API—it creates a dialog box in the browser window asking the user for input. Node.js has no browser window, so prompt is not defined. The error message would be: ReferenceError: prompt is not defined. To fix this in Node.js, the student could either hardcode the name (e.g., let name = "Alice";) or use Node's built-in readline module to read input from the terminal. The key lesson is that you must check which environment you're targeting and use the appropriate APIs for that environment.

Question 4: APPLIED

You're building a web page that shows a student's quiz grade. The page has a paragraph element with the id result. You want your JavaScript to calculate the percentage (score ÷ total × 100) and display it inside that paragraph. Write the HTML file with a script tag containing the JavaScript. Then explain why this specific approach would NOT work if you tried to run the JavaScript file with Node.js.
Show answer
Here's the complete HTML file: <!DOCTYPE html> <html><body> <h1>Quiz Result</h1> <p id="result"></p> <script> let score = 17; let total = 20; let percent = (score / total) * 100; document.getElementById("result").textContent = "You scored " + percent + "%"; </script> </body></html> This would not work in Node.js because document is a browser-only object representing the HTML page. Node.js has no HTML document to interact with, so document.getElementById() would throw a ReferenceError. The calculation itself (score ÷ total × 100) would work fine in Node, but displaying it in a web page paragraph requires the DOM, which only exists in the browser.

Question 5: CRITICAL THINKING

Before Node.js was created in 2009, JavaScript could only run in browsers. Explain how this limited what developers could build with JavaScript. Then argue why the ability to run JavaScript in both environments (browser and server) was a game-changer for the software industry. Consider at least two practical benefits.
Show answer
Before Node.js, JavaScript was confined to client-side scripting—it could only make web pages interactive after they loaded in the browser. Developers who wanted to build the server side of a web application had to learn a completely different language like PHP, Ruby, or Java. This meant teams needed different specialists for front-end and back-end work, and code couldn't be shared between the two layers. Node.js changed this in at least two major ways. First, it enabled full-stack JavaScript development, meaning a single developer could write both the browser code and the server code in the same language, reducing the learning curve and allowing code reuse (e.g., data validation logic). Second, it opened up entirely new use cases for JavaScript: developers could now build command-line tools, desktop applications (via Electron), and real-time servers (via WebSockets) all in JavaScript. This also created a unified ecosystem—npm packages can be used in both environments, dramatically accelerating development speed across the industry.

SUMMARY

Lesson Summary

Summary

JavaScript is a single language that runs in two main runtime environments. The browser environment lets you run code in the DevTools console for quick tests or embed it in HTML files using script tags to build interactive web pages. Browser JavaScript has access to the DOM, window, alert(), and prompt(), but it is sandboxed for security and cannot access local files.

The Node.js environment runs JavaScript outside the browser using the V8 engine. You execute files by typing node filename.js in the terminal. Node.js provides access to the file system, HTTP server creation, and system-level tools—but it has no DOM and cannot display web pages. The core language—variables, loops, functions, console.log()—works identically in both places. Understanding which environment you're working in is essential for knowing which tools are available to your code.

Varsity Tutors • Computer Programming 1 (JavaScript) • Running JavaScript (Browser vs. Node)