completefrontend
Open lab My progress
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 pagePut a script in a page, in a place where the browser runs it at the right time.
  • 02
    Load code from app.jsUse a script tag with src, and know what defer changes.
  • 03
    Run code with Node.jsMake hello.js, run it with node hello.js, and know the REPL when you see it.

Your first script

Hello, world! is a tiny first program. Many developers write it first when they learn a new language. It only prints a short message. But it checks three important things:

  • Your code is in the right place.
  • The right program is running it.
  • You can see what it prints.

In this lesson you run JavaScript in two places: a web page in the browser, and Node.js. A program that runs your JavaScript is called a host. You met hosts in the Engines, runtimes & hosts lesson. Both hosts understand the same JavaScript language. But each host gives your code different tools.

What a script is

A script is JavaScript code that a host runs. It can be written inside a web page, or saved in its own file.

  • The browser runs the scripts it finds in <script> tags in a page's HTML.
  • Node.js runs a script file when you type a command such as node hello.js in the terminal.
Real-life analogyA note taped inside a cookbook

You are reading a cookbook. Someone has taped a note between two paragraphs. You stop, do what the note says, then carry on reading. The browser treats a script tag the same way. It reaches the tag, runs the code, then carries on reading the page.

In real life: You read the cookbook from top to bottom
In JavaScript: The browser reads the HTML from top to bottom
In real life: A note says: stop and do these steps now
In JavaScript: A <script> tag says: run this JavaScript now
In real life: A note says: the steps are on the card called app.js
In JavaScript: <script src="app.js"> loads the code from another file

You will also use console.log a lot. It prints a message for you, the developer. Visitors to the page don't see it. The Why JavaScript? lesson already used it. Here you'll learn exactly what it can print.

The script tag

INTERACTIVE

The browser reads an HTML page from top to bottom. When it reaches a <script> tag, it stops and runs the code right there. Then it carries on reading the page.

Here is the smallest page with a script in it. Code written between <script> and </script> is called an inline script.

A page with a script inside itPop 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>

Lines 5 to 7 are the script. When the browser reaches line 5, it runs line 6. Line 6 prints Hello, world! in the Console. The Console is a panel in the browser's developer tools, called DevTools. It shows the messages your code prints.

Inline scripts are handy for tiny tests, because you see the code right where it runs. In real projects, you move the code into its own file. That keeps the HTML and the JavaScript easy to read.

Where you put the script matters. A script runs the moment the browser reaches it. Say the script looks for a button that comes later in the page. The button isn't there yet, so the search gives back null. null means "nothing was found".

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 the page from top to bottom. This script is in the head, so it runs before the browser reaches the button. querySelector finds nothing and logs null.

The preview is a sandboxed iframe: a small page inside this page that may run scripts but can't reach anything else. It runs only these prepared examples. Its logs are sent back here, and only messages from this iframe are shown.

The code in the playground uses document.querySelector("button"). document is the browser's object for the page. querySelector searches the page and gives back the first button it finds. Pick a setup, then press Run page:

  • head: the script is in <head>, above the button. It logs null, because the browser hasn't reached the button yet.
  • end of body: the script comes after the button. It logs Press me, the button's text.
  • head + defer: the script is in its own file, loaded with defer. defer tells the browser to run the file only after it has read the whole page. So it also logs Press me.

The inline and src buttons choose where the code lives: inside the tag, or in its own file. You'll meet src in the next section.

Two pages, read from top to bottom. Left: the script comes before the button, so it logs null. Right: the script comes after the button, so it logs Press me.<script> in headpage<script><button>logs null<script> at the endpage<button><script>logs Press me
The browser reads a page from top to bottom and runs a script as soon as it reaches it. On the left, the script runs before the button exists, so it finds nothing: null. On the right, the button is already there.

Load a script from a file with src

COMPARE

An external script is JavaScript kept in its own file, such as app.js. The HTML page doesn't hold the code. It only holds a <script> tag with src in it. src is short for "source". It tells the browser which file to load.

A setting written inside a tag, like src, is called an attribute.

The table compares the two kinds of script. Read each row as a question, then the answer for each kind.

Inline script or external script: how they differ
QuestionInline scriptExternal script with src
Where is the JavaScript?Between the opening <script> and the closing </script> tag.In another file, usually app.js.
When is it a good choice?For tiny examples and quick tests.For real projects and code you use again.
Can it use defer?No. defer only works for scripts loaded with src.Yes: <script src="app.js" defer></script>.
What if the tag has src and code inside it?That can't happen here: an inline script has no src.The browser ignores the code inside the tag.
index.html: the page points to app.jsPop out in the code editor (opens in a new tab)HTML
<!doctype html>
<html>
  <body>
    <h1>Hello page</h1>
    <script src="app.js"></script>
  </body>
</html>
app.js: the code that runsPop out in the code editor (opens in a new tab)JavaScript
console.log("Hello, world!");

Line 5 of index.html is the script tag. It has no code inside. Its src says the code is in app.js. The browser loads app.js and runs its one line, which prints Hello, world!.

The page index.html holds a tag that says src, app.js. An arrow goes from it to the file app.js, which holds the line console.log Hello, world.index.htmlsrcapp.jspoints to the fileapp.jsconsole.log("Hello, world!");the code that runs
The script tag in index.html holds no code. Its src only says which file to load. The browser loads app.js and runs the code inside it.
Code inside a tag with src is ignored

If a script tag has src, the browser ignores any code written between its opening and closing tags. So write one of these, not both:

  • a tag with src and nothing inside: <script src="app.js"></script>
  • an inline script, with the code inside and no src

Read a program one line at a time

STEP THROUGH

A program runs in order, one line after another. Here is a tiny program with three lines. Each line has one job:

  • Line 1 stores a name.
  • Line 2 builds a greeting from that name.
  • Line 3 prints the greeting.

A variable is a name that holds a value, so a later line can use it. Line 1 makes a variable called name and puts the text "Asha" in it. Line 2 joins three pieces of text with plus signs and puts the result in a new variable, greeting. Line 3 doesn't build anything. It reads greeting and sends its value to the Console.

Step through a greeting
Step 0 of 3Ready
Your turn: follow the blue line

This replays a recording of a small JavaScript program. Step through it to see each line use the value from the line before.

Running in
  1. script
Next: line 1
const greeting = "Hello, " + name + "!";console.log(greeting);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the name stored on line 1.

Changing the name starts the replay again from line 1.

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.

Press Step to go through the program one line at a time. Pick another name to see the steps change, and Reset to go back to Asha. The label on each step says what happened: a value was stored, a new value was made, or a result was printed. The player replays a recording of this small program. It doesn't pause the browser's real JavaScript engine.

Line 1 puts the text Asha in a box called name. Line 2 uses it to fill a box called greeting with Hello, Asha!. Line 3 prints Hello, Asha! in the Console, without quote marks."Asha"nameline 1"Hello, Asha!"greetingline 2ConsoleHello, Asha!line 3
Each variable is like a labelled box that holds one value. Line 2 reads name to build the greeting. Line 3 prints it. The Console shows the text without the quote marks.
The greeting program as a filePop out in the code editor (opens in a new tab)JavaScript
const name = "Asha";
const greeting = "Hello, " + name + "!";
console.log(greeting);

Save these three lines in a file, run it with Node.js, and it prints Hello, Asha!. The quote marks on lines 1 and 2 are part of the code. They show JavaScript where the text starts and ends. The printed message has no quote marks.

Print messages with console.log

STEP THROUGH

console.log(...) prints values in the Console. The Console is for developers; visitors to your page never see it. While you learn, it is your main way to check things, such as:

  • Did this file run at all?
  • What value does this variable hold?
  • Which part of the code ran?

console is an object the host gives you. log is a method of it: a function that belongs to an object. The dot in console.log means "the log that belongs to console".

Print one messagePop out in the code editor (opens in a new tab)JavaScript
console.log("Tea is ready");

The text between the quote marks is a string: a piece of text in your code. The call sends the string to the Console. The Console shows Tea is ready, without the quote marks. A log like this is the quickest way to check that your code reached a certain line.

The values inside the brackets of console.log(...) are called arguments. console.log can print:

  • a string, like "Hello, world!"
  • a number, like 5
  • the result of an expression: a piece of code that works out a value, like 2 + 3
  • several arguments at once, separated by commas
  • a template string: text between backticks, `, with values put in where it says ${...}

First guess what each line below prints. Then step through the recorded run. Change total on line 2 and watch: only the lines that use total print something different. The Console prints several arguments in order, with a space between them. Other consoles may space them a little differently.

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

Guess what each line prints. Then step through the recorded run and compare your guesses with what the Console shows.

Running in
  1. script
Next: line 1
const total = 5;console.log("Hello, world!");console.log(2 + 3);console.log("Total:", total);console.log(`${name} has ${total} tabs open.`);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Change the value stored on line 2.

Changing the value starts the replay again from line 1.

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.

Commas keep each value separate, so one log can show several labelled values. console also has two methods for messages that need attention:

  • console.warn is for something a developer should check.
  • console.error is for something that failed.

Neither one stops your program. They only print a message.

Label values, then print a warning and an errorPop out in the code editor (opens in a new tab)JavaScript
const order = "tea";
const total = 3;

console.log("Order:", order, "Total:", total);
console.warn("Check the total before paying.");
console.error("Payment could not be completed.");

Lines 1 and 2 store the order details. Line 4 passes four arguments, so the Console shows Order: tea Total: 3. Line 5 prints a warning, and line 6 prints an error. Browser DevTools shows these two in a different style, so they stand out. The text is still the message you wrote. You'll learn more console tools in Talking to the user.

Why the console may show undefined

Type console.log("Hi") into the browser Console, or into Node's REPL (you'll meet it below). It prints Hi. Then the prompt may also show undefined. That is the value the console.log call gives back. It is not an error.

Run a file with Node.js

TERMINAL

The browser is one host for JavaScript. Node.js is another. Node.js is a program that runs JavaScript files on your computer, with no browser and no web page. You start it from the terminal: a window where you type commands instead of clicking.

Real-life analogySame recipe, different kitchen

You can follow the same recipe in your kitchen or in a friend's kitchen. The steps are the same. But the drawers hold different tools. JavaScript works like that too. 2 + 3 works in both places. document.querySelector only works in a browser page, because only a page has a document.

In real life: The steps of the recipe
In JavaScript: The JavaScript language: strings, numbers, 2 + 3
In real life: Your kitchen, with its own drawers
In JavaScript: The browser: document, window, buttons on the page
In real life: A friend's kitchen, with different drawers
In JavaScript: Node.js: the terminal, files, and packages
hello.js: a file for Node.js to runJavaScript
console.log("Hello from Node!");
console.log(2 + 3);

Save these two lines in a file called hello.js. Line 1 prints Hello from Node!. Line 2 works out 2 + 3 first, then prints 5.

Run hello.js, then try the REPL, in a terminalbash
$ 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

In plain words:

  • The $ at the start of a line is the terminal's prompt. You don't type it.
  • Line 1, cat hello.js, shows what is inside the file. Lines 2 and 3 are the file.
  • Line 5, node hello.js, runs the file. Lines 6 and 7 are what it prints.
  • Line 9, node on its own, opens the REPL. The REPL is a prompt where you type one line of JavaScript and see the result straight away. REPL is short for read, evaluate, print, loop.
  • Line 11 runs a log in the REPL. Line 12 is the message. Line 13 is the undefined you met above.
  • Line 14, .exit, closes the REPL. Pressing Ctrl + C twice also closes it.
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

Put each piece of code in the right group: does it work in the browser, in Node.js, or in both? Each card explains why.

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

A plain Node.js script has no web page, so document and window don't exist. Run console.log(document.querySelector("button")); in Node.js, and it throws an error: it stops and reports ReferenceError: document is not defined. A ReferenceError means JavaScript can't find a name you used.

Your JavaScript goes to two places. A browser page has document and can find buttons. A terminal running Node.js has no document but can read files.your JavaScriptbrowser pagehas documentcan find buttonsterminal: Node.jsno documentcan read files
The same JavaScript language runs in both places. A browser page gives your code document, so it can find buttons. Node.js runs in a terminal with no page, so there is no document. It can read files instead.

Where you'll use this

You need a script tag whenever a page should do something. For example:

  • A portfolio site loads app.js to open a menu.
  • While you build a form, you log the values to check them.
  • A coding exercise asks you to run node solution.js, so the terminal can check your answer.
A starter page and its app.js, shown as two filesHTML
<!-- 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 box shows two files. The // app.js line marks where the second file starts. To try it:

  1. Save lines 2 and 3 as index.html.
  2. Save lines 6 and 7 as app.js, in the same folder.
  3. Open index.html in the browser and look in the Console.

defer makes sure the button exists before app.js looks for it. The log shows what the code found. In later lessons, your code will change the page itself instead of only logging.

When nothing prints

Sometimes your first script seems to do nothing. Don't try to guess ten possible problems at once. Check one thing at a time:

  1. Add one console.log at the top of the file.
  2. Refresh the page.
  3. Look in the Console in DevTools.

That first message answers one clear question: did this JavaScript file run at all?

Two useful first checksPop out in the code editor (opens in a new tab)JavaScript
console.log("app.js started");

const save = document.querySelector("#save");
console.log("Found save button:", save);

Line 1 should print app.js started. If it doesn't, check two things:

  • The src in the script tag spells the file name exactly right.
  • The Console you are looking at belongs to the page you refreshed.

A log is only a short-term check. Once you have found the problem, you can delete it.

Line 4 answers the next question: did the search find the button? Line 3 searches for "#save". An id is a name you give to one part of the page, such as a button. #save means "the part whose id is save". If the page has <button id="save">Save</button> and the script uses defer, the Console shows the button. If it shows null, check:

  • the text inside querySelector, here "#save"
  • the button's id in the HTML
  • whether the script ran before the browser read the button

Two small typing mistakes can stop a first program before it prints anything:

  • Text needs quote marks around it.
  • Capital letters matter. JavaScript treats log and Log as two different names.
Text without quotes is read as a namePop out in the code editor (opens in a new tab)JavaScript
console.log(Hello);

Without quote marks, JavaScript thinks Hello is the name of a variable, not text. There is no variable called Hello, so it throws ReferenceError: Hello is not defined. To print the text, write console.log("Hello").

Use lowercase console.logPop out in the code editor (opens in a new tab)JavaScript
console.Log("Tea is ready");

console has a method called log, but none called Log. The capital L makes it a different name. So the call throws TypeError: console.Log is not a function. Here, a TypeError means you tried to call something that isn't a function. Read the first error message before you change anything. It often points straight at the typo.

The table below puts these checks in order. Find the row that matches what you see in the Console, then do the check in the last column.

What to check when a first script seems to do nothing
What you see in the ConsoleThe question to askWhat to check first
No app.js started message.Did the file run?The src in the script tag, the spelling of the file name, and that you are looking at the right Console.
app.js started, then null.Did the search find the button?The id in the HTML, the text inside querySelector, and whether the script ran too early.
The log you expected.Did this line run?Yes, it did. Move on to the next small question.

The same steps work in Node.js. Put console.log("hello.js started") at the top of the file, run node hello.js, and read the first line it prints. In the browser, the Console shows messages from the page. With Node.js, the terminal shows messages from the file it ran.

Common mix-ups

Here are five beliefs that sound right but aren't.

"A script in the head can see the whole page."

No. A normal script in the head runs before the browser reads the body, so the parts of the page further down don't exist yet. Put the script at the end of the body, or use defer.

"src adds its file to the code inside the tag."

No. When a script tag has src, the browser ignores any code inside that same tag.

"console.log changes the page."

No. It only prints in the Console. Visitors don't see it on the page.

"Node.js and the browser give my code the same tools."

No. Both run the same JavaScript language, but the tools differ. Browser code has document. Node.js code has tools for reading files.

"Typing node always runs my file."

No. node on its own opens the REPL. To run a file, add its name: node hello.js.

Practice: run Hello, world

7 EXERCISES

The exercises start with a script in a page and end with a small order check. Guess the answer first, then use the hints if you get stuck.

Exercise 1 · Warm-upHello, world inside a page

Make a file called index.html. Add an inline script that logs Hello, world!. What does the Console show?

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 a file called app.js. Then 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.js

        Make a file called 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 never logs hi. Which part does the browser ignore?

          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.

            Exercise 6 · ChallengeGreet a visitor

            A page knows a visitor's name. Write three lines that:

            • store "Asha" in a variable,
            • build the text Hello, Asha!,
            • log the finished greeting.

            Guess the exact text before you run it.

            Starter codePop out in the code editor (opens in a new tab)JavaScript
            const name = "Asha";
            const greeting = "Hello, " + name + "!";
            console.log(greeting);

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

              Exercise 7 · ChallengeCheck an order

              A checkout page needs a quick check before payment. Run the starter code. What exactly does the first line print?

              Then say when you would use each of the other two messages: one is something to check, and one reports a payment that failed.

              Starter codePop out in the code editor (opens in a new tab)JavaScript
              const order = "tea";
              const total = 3;
              
              console.log("Order:", order, "Total:", total);
              console.warn("Check the total before paying.");
              console.error("Payment could not be completed.");

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

                Quiz: check your understanding

                8 QUESTIONS

                For each question, guess first, then pick an answer. Each answer explains why it is right or wrong.

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

                  Choose an answer to see the explanation.

                2. Question 2 of 8What 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 8Why put <script src="app.js" defer></script> in the head?

                  Choose an answer to see the explanation.

                4. Question 4 of 8What 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 8Which command runs a JavaScript file named hello.js with Node?

                  Choose an answer to see the explanation.

                6. Question 6 of 8What 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 8What is the Node REPL?

                  Choose an answer to see the explanation.

                8. Question 8 of 8What happens when this tries to log text without quote marks?

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

                  Choose an answer to see the explanation.

                Key takeaways

                A script is JavaScript that a host runs. Where you put it, and which host runs it, decide what it can do.

                • A <script> tag runs JavaScript in a browser page, at the point where the browser reaches it.
                • src loads the code from a separate file. defer waits until the browser has read the whole page.
                • console.log prints messages for developers: strings, numbers, results of expressions, and several values at once.
                • node hello.js runs a file with Node.js. node on its own opens the REPL.
                • The browser gives your code document. A plain Node.js script doesn't have it.

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

                Coming next: Statements, comments & semicolons. It shows how a script is split into single instructions, and how to leave notes in your code.

                CompleteFrontend Clear concepts. Working examples.