Introduction to JavaScript
HTML gives a page structure. CSS gives it style. JavaScript gives it behavior. Every time you click a button and something changes without the page reloading — that's JavaScript at work.
Adding JavaScript to a Page
You include JavaScript in HTML using a <script> tag. The best place for it is at the bottom of the <body>, after all your HTML content:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
console.log("JavaScript is running!");
</script>
</body>
</html>
Placing the script at the bottom ensures the HTML elements exist before JavaScript tries to interact with them.
External Script Files
For larger projects, you write JavaScript in a separate .js file and link to it:
<script src="script.js"></script>
This keeps your code organised and easy to maintain.
console.log
console.log() is your best friend when learning JavaScript. It prints values to the browser's developer console so you can see what's happening:
console.log("Hello, World!");
console.log(42);
console.log(true);
console.log(2 + 3); // 5
Open the browser console by pressing F12 (or Cmd+Option+I on Mac), then click the Console tab. This is where all your console.log messages appear.
Your First Script
Let's write a script that changes the text on a page when you click a button:
<h1 id="title">Hello!</h1>
<button onclick="changeText()">Click me</button>
<script>
function changeText() {
document.getElementById("title").textContent = "You clicked the button!";
}
</script>
Don't worry if you don't understand every part yet — you'll learn all of it step by step. For now, notice that JavaScript can find elements on the page and change them.
Try It Yourself
Hello!
Click the button below.
function changeText() { document.getElementById("title").textContent = "You clicked it!"; document.getElementById("desc").textContent = "JavaScript changed this text."; }Comments
Comments are notes in your code that the browser ignores. Use them to explain what your code does:
// This is a single-line comment
/*
This is a
multi-line comment
*/
console.log("This runs"); // inline comment
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.