cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Hello, world!

Run your first JavaScript script in a browser page and with Node.js, using script tags, src files, and console.log.

By the end, you can
  • 01
    Run code in a pagePlace an inline script where the browser can run it safely.
  • 02
    Move code to app.jsUse a script tag with src and know what defer changes.
  • 03
    Run code with NodeCreate hello.js, run node hello.js, and recognize the REPL.

Your first script

Hello, world! is the tiny first program many developers write in a new language. It does not build an app yet. It proves the most important thing: your code is in the right place, the right program is running it, and you can see the result.

In this lesson you will run JavaScript in two hosts: a browser page and Node.js. You met the idea of hosts in Engines, runtimes & hosts; now you will use it. The same JavaScript language can run in both places, but each host gives it different tools.

Definition

A script is a file or block of JavaScript instructions. The browser runs scripts from HTML <script> tags. Node.js runs scripts from the terminal with commands such as node hello.js.

Real-life analogyA script tag is a note inside a book

Imagine reading a cookbook. When a note is taped between two paragraphs, you stop reading and follow the note. A script tag works like that: the browser reaches it, runs the instructions, then continues reading the HTML.

In real life: A reader moves through a recipe line by line
In JavaScript: The browser parses HTML from top to bottom
In real life: A note says, stop and follow these instructions
In JavaScript: A <script> tag tells the browser to run JavaScript
In real life: A sticky note says, see the card named app.js
In JavaScript: <script src="app.js"> loads another file

Where the analogy stops: A person can flip ahead in a book whenever they want. A normal browser parser follows stricter timing rules, so a script may run before later HTML exists unless you place it later or use defer.

You will also use console.log. It prints a message for developers, not for visitors on the page. Earlier, the Why JavaScript? lesson used it in the first five lines; here you will slow down and learn exactly what it can print.

The script tag

INTERACTIVE

The browser reads HTML from top to bottom. When it meets a normal inline script, it runs the code right there. That timing matters. If the script tries to find a button before the browser has read the button's HTML, the answer is null: nothing was found.

Smallest inline scriptPop out in the code editor (opens in a new tab)HTML
<!doctype html>
<html>
  <body>
    <h1>Hello page</h1>
    <script>
      console.log("Hello, world!");
    </script>
  </body>
</html>

Inline scripts are useful for tiny experiments and examples because the JavaScript is visible right where it runs. In real projects, you quickly move code into its own file so HTML and JavaScript stay readable.

Build and run a tiny page
<!doctype html><html>  <head>    <script>      const button = document.querySelector("button");      console.log(button);    </script>  </head>  <body>    <button>Press me</button>  </body></html>
Page previewsandboxed iframe
Captured consoleReady

No logs yet. Press Run page.

Try it yourself
Script setup:

The browser reads top to bottom. A normal head script runs before the body, so querySelector cannot find the button yet and logs null.

The iframe is sandboxed with allow-scripts, and it runs only these predefined snippets. Logs are posted back to this page and accepted only from this iframe.

Try the first setup: script in <head>. It logs null because the browser has not reached the button yet. Move the script to the end of <body>, and it logs Press me. Use defer with an external script, and it also logs Press me because deferred scripts run after the HTML has been parsed.

External scripts with src

COMPARE

An external script keeps JavaScript in a separate file. The HTML contains a pointer, and the browser requests the file named by src. That pointer is the sticky note version of the script tag: see the instructions in app.js.

Inline script vs external script
QuestionInline scriptExternal script with src
Where is the JavaScript?Between the opening and closing script tagsIn another file, usually app.js
Best forTiny examples and one-off demosReal projects and reusable code
Can it use defer?No, defer is for external scriptsYes: <script src="app.js" defer></script>
What if the tag has src and text inside?Not applicableThe inline text is ignored for execution
<!doctype html>
<html>
  <body>
    <h1>Hello page</h1>
    <script src="app.js"></script>
  </body>
</html>
console.log("Hello, world!");
Important edge case

If a script tag has src, code written between its opening and closing tags is ignored for execution. Write either <script src="app.js"></script> or an inline script, not both.

console.log

STEP THROUGH

console.log(...) prints values to a developer console. It is how you leave breadcrumbs for yourself while learning: did this file run, what value did this variable hold, which branch happened?

It can print strings, numbers, expressions, several arguments separated by commas, and strings built from variables. Predict each line below, then step through the recorded run. Change total and watch only the lines that read total change.

Step through console.log
Step 0 of 6Ready
Your turn: follow the blue line

Predict each log. Then step through the real recorded run and compare your prediction with the console output.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const total = 5;console.log("Hello, world!");console.log(2 + 3);console.log("Total:", total);console.log(`${name} has ${total} tabs open.`);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Change the value stored on line 2.

Changing the value starts a fresh recorded run.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Why the console may show undefined

In a browser console or the Node REPL, console.log("Hi") prints Hi, then the prompt may show undefined. That extra word is the return value of console.log itself. It is not an error.

Running with Node.js

TERMINAL

The browser is one kitchen for JavaScript. Node.js is another. Running with Node is like taking the recipe out of the cookbook and cooking it in a different kitchen: the JavaScript language is familiar, but the tools around it change.

Real-life analogySame recipe, different kitchen

The recipe can say “chop onions” in either kitchen, but the drawers contain different tools. JavaScript expressions such as 2 + 3 work in both hosts; page tools such as document.querySelector only make sense in a browser page.

In real life: Recipe instructions
In JavaScript: The JavaScript language: strings, numbers, expressions
In real life: Cookbook kitchen
In JavaScript: Browser host: document, window, buttons
In real life: Apartment kitchen
In JavaScript: Node host: terminal input/output, files, packages

Where the analogy stops: Some tools exist in both kitchens, such as timers and console.log. Other tools belong to one host: document is browser-only, and Node's fs module is Node-only.

Example terminal sessionbash
$ cat hello.js
console.log("Hello from Node!");
console.log(2 + 3);

$ node hello.js
Hello from Node!
5

$ node
Welcome to Node.js ...
> console.log("Hi from the REPL")
Hi from the REPL
undefined
> .exit

Type node hello.js to run a file. Type node by itself and Node opens the REPL: an interactive prompt. Leave it with .exit or by pressing Ctrl + C twice.

Browser, Node.js, or both?
  • console.log("Hi")
  • document.querySelector("button")
  • reading a file with fs
  • alert("Saved!")
  • 2 + 2
  • setTimeout(() => console.log("later"), 1000)
Try it yourself
0 of 6 correct

Sort each feature by the host that provides it. The explanations remind you which tools belong to the language and which belong to a host.

Choose a category for every card. You can change an answer at any time; Reset clears them all.
Node has no document

A plain Node script does not create a web page, so document and window are not defined. Running console.log(document.querySelector("button")); in Node throws ReferenceError: document is not defined.

Where you'll use this

You use script tags whenever HTML needs behavior. A portfolio might load app.js to open a menu. A form might log test values while you build it. A coding exercise might ask you to run node solution.js so the terminal can check your answer.

Practical starter layoutPop out in the code editor (opens in a new tab)HTML
<!-- index.html -->
<button id="save">Save</button>
<script src="app.js" defer></script>

// app.js
const save = document.querySelector("#save");
console.log("Save button:", save);

This pattern is intentionally simple: keep HTML in index.html, keep JavaScript in app.js, use defer so elements exist, and use console.log to verify what your code found. Later lessons will replace logs with real page updates and user prompts.

Common misconceptions

“A script in the head can see the whole page.”

Not unless it waits. A normal head script runs before the body is parsed, so later elements do not exist yet. Use the end of body or defer.

“src adds to the inline code.”

No. When src is present, inline code inside the same script element is ignored for execution.

“console.log changes the page.”

It only writes to the developer console. Visitors do not see it as page content.

“Node and the browser have all the same globals.”

They share the JavaScript language, but the hosts differ. Browser code has document; Node code has file-system tools.

“Typing node always runs my file.”

node alone opens the REPL. To run a file, include its name: node hello.js.

Practice: run Hello, world

5 EXERCISES
Exercise 1 · Warm-upInline Hello, world

Create an index.html file with an inline script that logs Hello, world!.

Starter codePop out in the code editor (opens in a new tab)JavaScript
<script>
  console.log("Hello, world!");
</script>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeMove it to app.js

    Move the log into app.js and load it from index.html with src.

      Exercise 3 · PracticePredict the log

      What does this line print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      console.log("A", 1 + 1, "B");

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeRun with Node

        Create hello.js and run it from the terminal. What command do you type?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        console.log("Hello from Node!");

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFind the bug

          This tag does not log hi. Which part is ignored?

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          <script src="app.js">console.log("hi")</script>

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS
            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does a plain <script> tag do in an HTML page?

              Choose an answer to see the explanation.

            2. Question 2 of 7What does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("A", 1 + 1, "B");

              Choose an answer to see the explanation.

            3. Question 3 of 7Why put <script src="app.js" defer></script> in the head?

              Choose an answer to see the explanation.

            4. Question 4 of 7What happens if a script in the head runs document.querySelector("button") before the button exists?

              Choose an answer to see the explanation.

            5. Question 5 of 7Which command runs a JavaScript file named hello.js with Node?

              Choose an answer to see the explanation.

            6. Question 6 of 7What does this Node script throw?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(document.querySelector("button"));

              Choose an answer to see the explanation.

            7. Question 7 of 7What is the Node REPL?

              Choose an answer to see the explanation.

            Key takeaways

            • <script> runs JavaScript in a browser page.
            • src loads an external JavaScript file; defer waits until the HTML is parsed.
            • console.log prints developer messages: strings, numbers, expressions, and multiple arguments.
            • node hello.js runs a JavaScript file in Node; node alone opens the REPL.
            • Browser hosts have document; plain Node scripts do not.

            Remember the one-liner.
            A script is JavaScript handed to a host: HTML hands it to the browser; node hello.js hands it to Node.

            Up next: Statements, comments & semicolons.

            CompleteFrontend Clear concepts. Working examples.