Hello, world!
Run your first JavaScript script in a browser page and with Node.js, using script tags, src files, and console.log.
- 01Run code in a pagePut a script in a page, in a place where the browser runs it at the right time.
- 02Load code from app.jsUse a script tag with src, and know what defer changes.
- 03Run code with Node.jsMake hello.js, run it with node hello.js, and know the REPL when you see it.
Watch the video lecture
Full course on YouTube (opens in a new tab) ↗- Lecture 5Hello World and the console objectWatch on YouTube (opens in a new tab) ↗
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.
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.jsin the terminal.
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
INTERACTIVEThe 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.
<!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".
<!doctype html><html> <head> <script> const button = document.querySelector("button"); console.log(button); </script> </head> <body> <button>Press me</button> </body></html>No logs yet. Press Run page.
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 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 logsnull, 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.defertells the browser to run the file only after it has read the whole page. So it also logsPress 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.
null. On the right, the button is already there.Load a script from a file with src
COMPAREAn 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.
| Question | Inline script | External 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. |
<!doctype html>
<html>
<body>
<h1>Hello page</h1>
<script src="app.js"></script>
</body>
</html>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!.
index.html holds no code. Its src only says which file to load. The browser loads app.js and runs the code inside it.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
srcand 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 THROUGHA 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.
This replays a recording of a small JavaScript program. Step through it to see each line use the value from the line before.
script
const greeting = "Hello, " + name + "!";console.log(greeting);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.
name to build the greeting. Line 3 prints it. The Console shows the text without the quote marks.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 THROUGHconsole.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".
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.
Guess what each line prints. Then step through the recorded run and compare your guesses with what the Console shows.
script
const total = 5;console.log("Hello, world!");console.log(2 + 3);console.log("Total:", total);console.log(`${name} has ${total} tabs open.`);Commas keep each value separate, so one log can show several labelled values. console also has two methods for messages that need attention:
console.warnis for something a developer should check.console.erroris for something that failed.
Neither one stops your program. They only print a message.
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.
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
TERMINALThe 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.
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
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.
$ 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
> .exitIn 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,
nodeon 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
undefinedyou met above. - Line 14,
.exit, closes the REPL. PressingCtrl+Ctwice also closes it.
console.log("Hi")document.querySelector("button")- reading a file with fs
alert("Saved!")2 + 2setTimeout(() => console.log("later"), 1000)
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.
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.
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.jsto 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.
<!-- 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:
- Save lines 2 and 3 as
index.html. - Save lines 6 and 7 as
app.js, in the same folder. - Open
index.htmlin 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:
- Add one
console.logat the top of the file. - Refresh the page.
- Look in the Console in DevTools.
That first message answers one clear question: did this JavaScript file run at all?
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
srcin 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
idin 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
logandLogas two different names.
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").
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 you see in the Console | The question to ask | What 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 EXERCISESThe 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.
Make a file called index.html. Add an inline script that logs Hello, world!. What does the Console show?
<script>
console.log("Hello, world!");
</script><script>
console.log("Hello, world!");
</script>The script tag tells the browser to run the code inside it. The Console shows Hello, world!.
Move the log into a file called app.js. Then load it from index.html with src.
<script src="app.js"></script>
// app.js
console.log("Hello, world!");The browser sees src="app.js", loads that file, and runs the code inside it. Code in its own file is easier to find and change later.
What does this line print?
console.log("A", 1 + 1, "B");It prints A 2 B. First 1 + 1 becomes 2. Then console.log prints its three arguments in order.
Make a file called hello.js and run it from the terminal. What command do you type?
console.log("Hello from Node!");node hello.jsOpen the terminal in the folder that holds hello.js. Then node hello.js runs the file and prints Hello from Node!.
This tag never logs hi. Which part does the browser ignore?
<script src="app.js">console.log("hi")</script><script src="app.js"></script>
<!-- Put console.log("hi") inside app.js instead. -->Because src is set, the browser ignores console.log("hi") inside the tag. Move the code into app.js, or remove src to make it an inline script.
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.
const name = "Asha";
const greeting = "Hello, " + name + "!";
console.log(greeting);const name = "Asha";
const greeting = "Hello, " + name + "!";
console.log(greeting);Line 1 stores the name. Line 2 builds the full message. Line 3 prints it. These are the same three steps as the greeting program above.
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.
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.");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.");One log can show several labelled values, without joining them into one long string. console.warn and console.error make the next two messages stand out in DevTools.
Quiz: check your understanding
8 QUESTIONSFor each question, guess first, then pick an answer. Each answer explains why it is right or wrong.
Question 1 of 8What does a plain
<script>tag do in an HTML page?Choose an answer to see the explanation.
Question 2 of 8What does this print?
Read the code, then predictconsole.log("A", 1 + 1, "B");Choose an answer to see the explanation.
Question 3 of 8Why put
<script src="app.js" defer></script>in the head?Choose an answer to see the explanation.
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.
Question 5 of 8Which command runs a JavaScript file named hello.js with Node?
Choose an answer to see the explanation.
Question 6 of 8What does this Node script throw?
Read the code, then predictconsole.log(document.querySelector("button"));Choose an answer to see the explanation.
Question 7 of 8What is the Node REPL?
Choose an answer to see the explanation.
Question 8 of 8What happens when this tries to log text without quote marks?
Read the code, then predictconsole.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. srcloads the code from a separate file.deferwaits until the browser has read the whole page.console.logprints messages for developers: strings, numbers, results of expressions, and several values at once.node hello.jsruns a file with Node.js.nodeon 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.