Start using Javascript
Learn how to add JavaScript to a web page with the script tag, link external .js files, control loading with defer and async, and use the browser console.
What This Chapter Covers
This is your starting point for writing JavaScript. By the end of it you will know how to:
- add JavaScript directly to an HTML page with the
<script>tag, - move your code into a separate
.jsfile and link it, - control when a script runs with the
deferandasyncattributes, - write your first lines of code, and
- use the browser console to see output and find mistakes.
If you are brand new to the language, read the short Introduction to JavaScript first for the big picture, then come back here to start writing code.
Why You Need JavaScript
HTML describes the structure of a page and CSS styles it, but neither can react to a visitor. HTML alone lets people read text, watch videos, view images, and click links — it cannot do math, validate a form, or change the page after it has loaded. JavaScript adds behavior: it turns a static document into something interactive that can respond to clicks, typing, and other events.
Adding JavaScript to a page means you are writing a computer program. Most beginner scripts are short, but they share the same building blocks as larger programs: values, conditions, and step-by-step instructions. A good way to think before you code is to break a task into small steps. For example, to greet a visitor by name — "Welcome, John Doe!" — your program needs to:
- ask the visitor for their name,
- read the reply, and
- print the message on the page.
Once the steps are clear, you translate them into code. Learning the language is a lot like learning a spoken one: you pick up new words (let, if, function) and learn how to combine them.
How to Add JavaScript to a Page
The browser reads HTML top to bottom. To tell it "JavaScript is coming," you wrap your code in the HTML <script> tag. Everything between the opening <script> and closing </script> is run as JavaScript:
A "Hello, world!" script inside HTML
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script>
alert('Hello, world!');
</script>
<p>...After the script.</p>
</body>
</html>A <script> tag can hold the code itself (called inline code) or point to an external file with the src attribute (covered in the next section). You can place <script> tags in the page's <head> or anywhere in the <body>.
Where to put the <script> tag
A script blocks parsing while it runs, so placement matters:
- Just before the closing
</body>tag is the simplest safe spot. By the time the script runs, the HTML above it already exists, so the code can find page elements. - In the
<head>keeps your code organized in one place, but a plain<script>there runs before the body is parsed — so it cannot yet see the page's elements. To fix that, use thedeferattribute (see below).
Old <script> attributes you may still see
Modern scripts rarely need any attributes, but two appear in older code:
type— HTML4 requiredtype="text/javascript". It is no longer needed; the modern standard reusestypeonly for JavaScript modules (type="module"), an advanced topic covered later.language—language="javascript"once declared the script language. JavaScript is the default, so this attribute is obsolete.
You can read about every available attribute in the chapter on HTML attributes.
Controlling when a script loads: defer and async
When the browser hits an external <script src="...">, it normally stops building the page, downloads the file, and runs it before continuing. On a page with several scripts this slows rendering. Two attributes change that behavior:
defer— download the script in parallel and run it only after the HTML is fully parsed, in the order the scripts appear. This is the recommended default for scripts that touch the page.async— download in parallel and run as soon as it is ready, without guaranteeing order. Best for independent scripts (analytics, ads) that do not depend on other code or on the page being ready.
<!-- Runs after the page is parsed, keeps order -->
<script defer src="main.js"></script>
<!-- Runs whenever it finishes downloading, order not guaranteed -->
<script async src="analytics.js"></script>Both attributes only apply to external scripts (src). For inline code, simply place the <script> at the bottom of the <body>.
External JavaScript Files
Inline code is fine for a quick demo, but real projects keep JavaScript in separate .js files. Copying the same code into every page is hard to maintain — if you fix a bug you would have to edit every page. An external script lives in one .js file that many pages can share, so you write it once and the browser can even cache it for speed.
To use an external file, point the <script> tag's src (source) attribute at it and leave the tag empty:
Linking a script in the same folder
<script src="W3DocsScript.js"></script>The path in src works like any other URL in HTML. It can be:
- Relative to the current page —
my-script.js(same folder) orjs/my-script.js(a subfolder). - Absolute (site-root) path — starts with
/:
<script src="/path/W3DocsScript.js"></script>- A full URL, useful for libraries hosted on a CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>To load several files, use one <script> tag per file. They run top to bottom:
<script src="/W3DocsScript1.js"></script>
<script src="/W3DocsScript2.js"></script>A common gotcha: a single <script> tag cannot have both a src attribute and inline code. If src is set, anything between the tags is ignored:
src set — the inline alert never runs
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script src="W3DocsScript.js">
alert("Hello, world!"); // the content is ignored, because src is set
</script>
<p>...After the script.</p>
</body>
</html>To use both an external file and inline code, split them into two separate tags:
Two tags: one external, one inline
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script src="W3DocsScript.js"></script>
<script>
alert("Hello, world!");
</script>
<p>...After the script.</p>
</body>
</html>Your First JavaScript Program
Let's write a complete first program. Create an HTML file, and just before the closing </body> tag add a <script> with a single line that pops up a message:
An alert() dialog
<!DOCTYPE HTML>
<html>
<head>
<title>My First Script</title>
</head>
<body>
<p>Before the script...</p>
<script>
alert('Welcome to W3Docs');
</script>
</body>
</html>When you open this page in a browser, a dialog box appears with the text Welcome to W3Docs. The page pauses until you click OK; once the box closes, the rest of the page renders. alert() is handy for quick checks while learning, but it interrupts the user, so production code rarely uses it.
Writing Text on a Web Page
alert() shows a popup, but you often want to put text into the page itself. The classic teaching command for this is document.write(), which inserts whatever string you pass straight into the document as it loads:
Using document.write()
<!DOCTYPE HTML>
<html>
<head>
<title>document.write demo</title>
</head>
<body>
<h1>Writing to the document window</h1>
<script>
document.write('<p>Welcome to W3Docs!</p>');
</script>
</body>
</html>Like the alert() function, document.write() outputs whatever you place between its parentheses — here a <p> element, so the browser adds a new paragraph below the heading.
Heads up:
document.write()is fine for a first experiment, but avoid it in real projects. If it runs after the page has finished loading, it wipes out the entire document. Modern code updates the page through the DOM (for exampleelement.textContent = '...') instead.
The Browser JavaScript Console
Every modern browser ships with a built-in console — the most useful tool you have while learning. It shows messages you print, reports errors with the exact line number, and lets you type JavaScript and run it instantly.
Print to it with console.log(). Unlike alert(), it does not interrupt the page, and unlike document.write(), it never overwrites your document — so it is the go-to way to inspect values:
Logging to the console
<!DOCTYPE HTML>
<html>
<head>
<title>console.log demo</title>
</head>
<body>
<p>Open the console to see the message.</p>
<script>
console.log('Welcome to W3Docs');
console.log('2 + 2 =', 2 + 2);
</script>
</body>
</html>To open the console:
- Chrome / Edge:
Ctrl + Shift + J(Windows/Linux) orCmd + Option + J(Mac), or use the menu → More tools → Developer tools and pick the Console tab. - Firefox:
Ctrl + Shift + K(Windows/Linux) orCmd + Option + K(Mac). - Safari: enable the Develop menu in Settings → Advanced, then press
Cmd + Option + C.
For a deeper tour of debugging tools, see DOM debugging and tools.
Summary
- Add JavaScript with the
<script>tag — inline code goes between the tags; an external file goes in thesrcattribute (never both in one tag). - Place plain scripts just before
</body>, or usedeferon external scripts to run them after the page is parsed. - External
.jsfiles give you reuse and caching across many pages. alert()shows a popup,document.write()writes into the page (use sparingly), andconsole.log()prints to the console without disturbing the page.
Next, learn how to store data in JavaScript variables and how to document your code with comments.