Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 156 ยท Getting Started

Where JavaScript Runs

Run JavaScript in the browser console, in web pages with script tags, from .js files and with Node.js, and learn the difference between the language and its host.

JavaScript code needs something to run it. That "something" is a JavaScript engine: a program that reads your code and carries out the instructions. Every modern browser has one built in, and runtimes such as Node.js bring the same kind of engine to your computer and to servers.

In this lesson you will meet the main places JavaScript runs: the browser's developer console, <script> elements inside web pages, separate .js files and Node.js. You will also learn an idea that clears up a lot of confusion later: the difference between the JavaScript language and the environment that hosts it.

The browser console

Every desktop browser includes developer tools (DevTools), and DevTools include a console: a prompt where you can type JavaScript and run it immediately. Open it with:

  • Windows and Linux: F12 or Ctrl + Shift + J (Chrome, Edge), Ctrl + Shift + K (Firefox)
  • macOS: Cmd + Option + J (Chrome, Edge), Cmd + Option + K (Firefox), Cmd + Option + C (Safari, after turning on Show features for web developers in Settings โ†’ Advanced)

Type 2 + 2 and press Enter, and the console answers 4. This is called a REPL (read, evaluate, print, loop): it reads one line, evaluates it, prints the result and waits for the next line.

JavaScript
> 2 + 2
4
> "Hello".length
5
> let city = "Lisbon"
undefined
> city
'Lisbon'

Two things often surprise beginners:

  • After a line like let city = "Lisbon", the console prints undefined. That is not an error. Declaring a variable doesn't produce a value, so the console reports "no value", which is undefined.
  • The console runs code in the page you have open. Anything you change there, such as editing the page's text, only lasts until you reload. It's a scratchpad, not a place to keep programs.

The console is also where errors and console.log() messages from a page appear, which makes it your main debugging tool. The HTML lesson Viewing Source and Using DevTools gives a tour of the other panels.

JavaScript in a web page

To make JavaScript part of a page, you put it in a <script> element. You can write the code directly inside the element, or keep it in a separate file and point to it with src:

HTML
<!-- Inline code -->
<script>
  console.log("Hello from inside the page");
</script>

<!-- Code from a separate file -->
<script src="/js/app.js" defer></script>

Separate files are the normal choice for real sites: the code is easier to organize, can be shared by many pages, and the browser can cache it. A <script> with src must stay empty; any code you write between its tags is ignored.

Keeping code in external files pays off in four ways:

  • Separation of concerns: HTML describes structure, CSS appearance and JavaScript behavior, each in its own place, so you can change one without touching the others.
  • Reuse: one file can serve every page of the site, and you fix a bug once.
  • Caching: after the first visit the browser reuses the downloaded file, so later pages load faster. Inline code is downloaded again with every page.
  • Readability and maintenance: editors, linters and teammates handle a .js file far better than code buried in HTML.

Small page-specific snippets, such as a one-line initialization, are fine inline. The third place JavaScript can appear is an event-handler attribute such as onclick="..."; it works, but it mixes behavior into the markup, so the events lesson recommends addEventListener() instead.

When does the script run?

By default, the browser stops reading the HTML when it reaches a <script>, runs the code, then continues. That matters, because code can only work with elements the browser has already read. Run this example and look at the console output under the preview.

Script order matters

The first script finds nothing (null), because the heading doesn't exist yet. The second one finds it and changes it. Two attributes solve this ordering problem for external scripts, and you should use one of them on almost every script you load:

  • defer downloads the file in parallel and runs it after the whole document has been parsed, in the order the scripts appear.
  • type="module" loads the file as a JavaScript module. Modules are deferred automatically and unlock import and export, which you will learn in Modules: import and export.
HTML
<head>
  <script src="/js/app.js" defer></script>
  <!-- or -->
  <script type="module" src="/js/main.js"></script>
</head>

The HTML course covers every option, including async, in Adding JavaScript.

JavaScript files

A JavaScript file is a plain text file with a .js extension (modules sometimes use .mjs). It contains only JavaScript, with no <script> tags:

JavaScript
// app.js
const greeting = "Welcome back!";
console.log(greeting);

Write these files in a code editor such as VS Code, save them with UTF-8 encoding, and either link them from a page or run them with a runtime like Node.js.

Node.js and other runtimes

Node.js takes the V8 engine from Chrome and wraps it in a program you can run from a terminal. Once it's installed, you can run a file with one command, or type node on its own to get a REPL much like the browser console:

TEXT
$ node app.js
Welcome back!

Node.js made JavaScript a general-purpose language. People use it to build web servers and APIs, command-line tools, build systems for front-end code, and scripts that automate everyday tasks. Two newer runtimes, Deno and Bun, do the same job with different design choices, such as built-in TypeScript support. JavaScript also runs inside desktop apps (Electron), browser extensions, background web workers and many other hosts.

You don't need to install anything for this course. Every example runs right here on the page. But if you want to build JavaScript tools later, Node.js is the place to start, and Packages, npm and Build Tools explains that ecosystem.

Interpreted or compiled? How an engine runs your code

People call JavaScript "interpreted", but modern engines do both. They start running your code almost immediately, then compile the parts that run often into fast machine code. This is called just-in-time (JIT) compilation. Take V8, the engine in Chrome, Edge and Node.js, as the example. Its main stages are:

  1. Parse. The source text is turned into an abstract syntax tree. Functions that don't run yet are only pre-parsed, which keeps start-up fast. A syntax error is found here, before any line executes.
  2. Ignition, the interpreter. The tree becomes compact bytecode, and Ignition starts running it right away. While it runs it records how the code behaves, for example which types a function usually receives.
  3. TurboFan, the optimizing compiler. Functions that run a lot ("hot" code) are compiled to optimized machine code using those observations.
  4. Deoptimization. If an assumption turns out wrong (a function that always got numbers suddenly gets a string), the engine throws the optimized code away and falls back to bytecode.

So the engine makes a bet based on what it has seen. You don't have to manage any of this, but it explains two habits of fast code: keep a function's argument types consistent, and create objects with the same properties in the same order so the engine can treat them alike.

Also worth knowing: JavaScript runs your code on one thread, with an event loop that handles waiting (see Asynchronous JavaScript). The engine's own compiling and garbage collection happen on helper threads, so they don't block your code. Other hosts differ in the details (Firefox's SpiderMonkey has several tiers, Safari's JavaScriptCore has four), but the idea is the same: interpret first, optimize what is hot.

The language versus the host

Here is the key idea of this lesson. The JavaScript language, defined by the ECMAScript standard, includes things like variables, numbers, strings, functions, objects, arrays, Math and JSON. These work the same everywhere.

Everything that connects JavaScript to the outside world comes from the host environment instead:

  • Browsers provide document (the page), window, alert(), fetch(), localStorage and events.
  • Node.js provides process, file system access through modules like node:fs, and network servers.
  • Many features, such as console, setTimeout() and fetch(), are provided by both, but each host implements its own version.

So document.querySelector() is not "part of JavaScript". It's part of the browser's DOM API, which JavaScript can use when it runs in a browser. In Node.js there is no page, so there is no document. You can check what your current environment provides with typeof, which you will study in Data Types:

JS What does this host provide?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Our editors run in a browser, so document and window exist ("object"), while the Node.js names are "undefined". Run the same code in Node.js and the answers flip. typeof is handy here because, unlike just using a missing name, it never throws an error.

How the editors in this course run your code

The lessons use two kinds of editors, and now you can describe exactly what they do:

  • Console editors (js) take your code and run it as a classic <script> inside a hidden, sandboxed page. Their output panel shows everything you pass to console.log() and friends, plus any errors. A few lessons switch an editor into module mode, which allows import syntax and await at the top level.
  • Page editors (html) render your HTML in a visible, sandboxed preview, run its scripts, and show console output underneath.

Because console editors are not a REPL, they don't echo the value of each line. Compare the two styles in this example:

JS Expressions need console.log

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Only the two logged values appear. This is exactly how a .js file behaves in a web page or in Node.js too: scripts don't print anything unless you ask them to.

Use both tools. The lesson editors are perfect for focused experiments. The real browser console is great for poking at a live page: open it on any website and try document.title or document.querySelectorAll("a").length.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You type let score = 10 into the browser console and it prints undefined. What does that mean?

    The console prints the value of each line it runs. A declaration has no value of its own, so it reports undefined. The variable still exists and holds 10.
  2. 2. A script in the <head> (with no attributes) calls document.querySelector("main"). Why might it get null?

    A plain script runs as soon as it is reached, before later HTML has been parsed. Use defer or type="module" so the script runs after the document is ready.
  3. 3. Which of these is provided by the browser rather than by the JavaScript language itself?

    document is part of the browser's DOM API. Math, JSON and Array are built into the language and exist in every environment.
  4. 4. What is Node.js?

    Node.js wraps a JavaScript engine in a program you run from a terminal, adding host features such as file and network access.
  5. 5. A .js file contains only the line 5 + 5;. What does it print when it runs?

    Scripts calculate expressions but don't print them. Only an interactive console (a REPL) echoes values automatically. Use console.log(5 + 5) to see the result.

Summary

  • A JavaScript engine runs your code. Browsers have one built in; Node.js, Deno and Bun bring one to servers and your computer.
  • The browser console is a REPL: it runs one line at a time and prints each result.
  • In a page, code goes in a <script> element, inline or from a file with src. Use defer or type="module" so scripts run after the HTML is parsed.
  • The language (variables, functions, Math, JSON) is the same everywhere; the host adds things like document in browsers or process in Node.js.
  • Scripts and our console editors only show what you log with console.log().

Next: Statements, Expressions and Syntax โ€” the grammar rules of JavaScript.