This article covers what JavaScript is, how it works with HTML and CSS, what it's used for, and how to add it to a web page. We'll also run a few lines of JavaScript on a real page.
If you're new to HTML and CSS, the earlier articles "What is HTML?" and "What is CSS?" cover how a page is structured and styled. Have a look at those too if you like.
The Roles of HTML, CSS, and JavaScript
A web page is usually built from three technologies, and each has its own job:
- HTML gives the page its structure - headings, paragraphs, images, buttons, and so on.
- CSS gives the page its style - colors, fonts, spacing, and layout.
- JavaScript handles behavior - how the page responds and changes while you use it.
We used a house analogy in the CSS article: HTML is the frame and walls, CSS is the paint and furniture, and JavaScript is the wiring and appliances, the parts that make things happen when you flip a switch.
HTML and CSS alone can't rewrite the content of a page or decide what happens when a button is clicked. That's where JavaScript comes in. For example, it can update text after a click, or check a form before it's sent.
What Is JavaScript?
JavaScript is a programming language created at Netscape Communications in 1995. It was first supported in Netscape's browser, Netscape Navigator, and the following year, Microsoft's Internet Explorer 3.0 added the same kind of feature as "JScript".
Once JavaScript came along, web pages could do things they couldn't before, like checking what someone typed into a form, showing the current time, or even running a game. Today it's also used outside the browser, for example on servers with Node.js and in desktop apps.
Making a "Read More" Button with JavaScript
First, here's a simple example of what you can do with JavaScript. When you click the "Read more" button, the button disappears and the rest of the text appears in its place:
<!DOCTYPE html>
<html>
<body>
<p>Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do.</p>
<button id="readMore">Read more</button>
<p id="extraContent" style="display: none;">
Once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?"
</p>
<script>
const button = document.getElementById('readMore');
const extraContent = document.getElementById('extraContent');
button.addEventListener('click', function () {
extraContent.style.display = 'block';
button.style.display = 'none';
});
</script>
</body>
</html>
Text excerpt from Alice's Adventures in Wonderland by Lewis Carroll (1865), which is in the public domain. Source: Project Gutenberg.
When you click "Read more", you'll see the rest of the text appear right there on the page. This kind of thing is hard to do with HTML and CSS alone, but with JavaScript it only takes a few lines. You can also combine it with CSS to animate the text as it appears.
What Can JavaScript Do?
JavaScript runs inside the web browser, and the browser gives it access to a lot of features. Here are some of the things it's commonly used for:
- Change or add content on a page, like the "Read more" example above.
- Change styles, such as colors, sizes, or animations.
- Run your own code when the user does something, such as clicking, typing, or scrolling.
- And of course, it can do calculations, just like any other programming language.
It can do much more than this. We'll cover some of it later in this article.
In fact, JavaScript is already running on the page you're reading right now. An article page like this one doesn't need much of it. Sites with a lot going on, like video sites, chat apps, and social media, have much more JavaScript running behind the scenes.
Your First JavaScript
We'll get to the details of JavaScript as a language later. First, let's try running it in the browser. You don't need to install anything. Every major web browser has a JavaScript engine built in, so you can try it right away. Here are two ways to do it.
Trying It in the Browser Console
Major browsers also come with a console as part of their developer tools. You can type JavaScript code there and see the result right away.
Open your browser's developer tools (press F12, or right-click the page and choose "Inspect"), then click the Console tab. Type this and press Enter:
console.log('Hello, JavaScript!');
In Chrome, it looks like this:
console.log(...) is a built-in command that writes a message to the console.
While learning or testing, it's the easiest way to check what your code is doing.
It's used a lot in real development work, too.
The word "console" might sound technical,
but it's really just a handy extra feature for running JavaScript.
You'll also see undefined on the last line. You don't need to worry about it.
It just means console.log itself doesn't return any value.
So far, it just prints the text you gave it, so it might feel a little boring. Next, try this:
console.log('Hello, JavaScript!'.toUpperCase());
This time, the console shows HELLO, JAVASCRIPT!, all in capital letters.
Does that feel a little more like programming?
You can also try console.log(1 + 1). The console shows 2.
JavaScript is a programming language, so it can do calculations like this, too.
Tip:
The browser console automatically shows the result of the last thing you run.
For example, if you type just 10 + 20 (without console.log)
and press Enter, it shows 30.
For quick checks like this, you don't even need console.log.
This is also why you saw undefined earlier.
It's the result of console.log itself.
(We'll cover functions and return values in detail in a later article.)
Running It on a Page
The console is handy for quick tests, but on a real web page,
JavaScript usually shows text and content in elements on the page
(like a <div>), not in the console.
(What you print to the console is only visible in your own browser.)
Here's a small page with a counter.
Each time you click the button, the number goes up by one:
<!DOCTYPE html>
<html>
<body>
<p>Count: <span id="count">0</span></p>
<button id="countButton">+1</button>
<script>
const countButton = document.getElementById('countButton');
const countText = document.getElementById('count');
// Run this when the button is clicked
countButton.addEventListener('click', function () {
// Turn the current text into a number and add 1
const newCount = Number(countText.textContent) + 1;
// Show the new number
countText.textContent = newCount;
});
</script>
</body>
</html>
Each time you click "+1", the number on the page goes up by one.
The JavaScript code inside the <script> tag is what updates the number.
The code has a few new words, like const, but for now, the important one is document.getElementById.
It's how JavaScript gets hold of an HTML element, like a <span> or <div>,
so the code can change it.
Here, document.getElementById('count') finds the element whose id is count
(the <span> that shows the number).
The code then changes the text inside it to the new number.
Unlike many other programming languages, JavaScript can work directly with HTML and CSS.
Because it's built into the browser, it can easily change the web page you're looking at.
How to Add JavaScript to a Page
In the example above, the JavaScript was written inside a <script> tag.
That's one of a few ways to add JavaScript to a page. Here are the common ones.
In a <script> Tag
You can write JavaScript directly in your HTML, inside a <script> tag.
Everything between <script> and </script> is treated as JavaScript.
<!DOCTYPE html>
<html>
<body>
<h1>My Page</h1>
<script>
console.log('The page has loaded.');
</script>
</body>
</html>
In a Separate File
JavaScript can also be written in a separate file (usually with a .js extension)
and loaded with the src attribute on a <script> tag.
First, a file called my-script.js:
console.log('The page has loaded.');
Then link it from the HTML:
<script src="my-script.js"></script>
A separate file is handy when the same code is shared across several pages, or when you want to keep the HTML easier to read. Either way, the code itself works the same.
Note:
Most of the examples in this article have the JavaScript inside a <script> tag rather
than in a separate file. That way you can open them in the SyncFiddle editor and run them as-is,
without setting up extra files.
Inline in an Attribute
A small piece of JavaScript can also go directly inside certain HTML attributes,
such as onclick:
<button onclick="console.log('clicked!')">Click me</button>
Clicking the button runs the code in the attribute, and clicked! appears in the console.
This is another way to write what the counter example did with
countButton.addEventListener('click', function () { ... }).
Both set what happens when the button is clicked.
The difference is whether you write it as an HTML attribute or in JavaScript code.
Writing it in an attribute is quick for short code like this.
But as the code gets longer, or the page has many buttons with their own onclick,
it can get hard to tell where everything is.
So it's also common to write the code inside a <script> tag
using addEventListener, like in the counter example.
Where to Put the <script> Tag
The browser reads a page from top to bottom,
and a <script> runs as soon as the browser reaches it.
So if your script uses an element on the page, that element has to come before the script.
Here's an example. The same code is written twice, once before the <h1> and once after it:
<!DOCTYPE html>
<html>
<body>
<script>
const heading = document.getElementById('heading');
if (heading) {
console.log(heading.textContent);
} else {
console.log('Heading not found');
}
</script>
<h1 id="heading">My Page</h1>
<script>
const heading2 = document.getElementById('heading');
if (heading2) {
console.log(heading2.textContent);
} else {
console.log('Heading not found');
}
</script>
</body>
</html>
When you run this, the console shows:
Heading not found
My Page
This code has const again, and now if too, but you don't need to worry about them for now.
const keeps a value so the code can use it later.
if works just like the English word: "if this is true, do this."
The important part of this example is whether heading and heading2 were found or not.
The first one, heading, wasn't found, so console.log('Heading not found') runs.
The second one, heading2, was found, so console.log(heading2.textContent) runs.
The first script runs before the browser has read the <h1>, so it can't find it yet.
The second script comes after the <h1>, so it can.
That's why the <script> is often placed just before the closing </body> tag.
By then, the rest of the page is already in place.
More Things JavaScript Can Do
The examples in this article were small, but JavaScript can do a lot more. For example:
- Loading data in the background (Ajax): Exchange data with a server, then update part of the page without reloading it.
- Checking forms: Find missing fields or mistakes in the format before a form is sent, or fill in an address automatically from a postal code.
- Using APIs: Play audio and video, or save small amounts of data on the device, with features built into the browser. With the user's permission, it can also use the camera and microphone, or get the device's location. You can use APIs from outside services, too, for example to show a map on your page.
-
Making web apps and browser games:
Start with something small, like a tool with a search box, and work up to a chat app if you like.
With the HTML
<canvas>element, you can also draw fast 2D and 3D graphics and make your own games, even in 3D.
You don't need to learn all of this at once. Most of it builds on what you saw in this article: find an element, wait for something to happen, then change the page.
Tip: API stands for Application Programming Interface. Simply put, it's a way for your code to use features from somewhere else, like an outside service or the browser itself. APIs aren't just for JavaScript. They're used in many other programming languages, too. For example, showing weather or news from another service on your own site is done through an API. The browser itself comes with many APIs too, so a few lines of JavaScript are often enough to add a feature.
Summary
- A web page is usually built from three technologies: HTML for structure, CSS for style, and JavaScript for behavior.
- JavaScript runs in the browser and can change the page after it loads, run code when the user clicks or types, exchange data with servers, and use the browser's built-in features (its APIs).
- Every major web browser can run JavaScript, so you don't need to install anything.
-
The console (in your browser's developer tools) is a quick place to try JavaScript.
console.log(...)prints a message there. -
You can add JavaScript to a page inside a
<script>tag, from a separate.jsfile using<script src="...">, or inline in an attribute likeonclick. -
A script runs as soon as the browser reaches it. That's why it's often placed just before
</body>.
Try It Yourself
Open the SyncFiddle Editor, paste in one of the examples above, and try changing it.
For example, change the message, rename the button, or add another console.log.