What is JavaScript?
JavaScript (JS) is the programming language of the web. HTML builds the structure, CSS styles it and JavaScript makes it interactive: menus, forms, animations, games and apps. It also runs on servers through Node.js.
Adding JavaScript to a page
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<button onclick="greet()">Click me</button>
<script>
function greet() {
document.getElementById("title").textContent = "Welcome to JavaScript!";
}
</script>
</body>
</html>You can also link an external file, which is the best practice for real projects:
<script src="app.js" defer></script>defer makes the script run after the page has loaded.
The browser console
Press F12 in your browser, open the Console tab and try:
console.log("Hello, world!");console.log() prints values. You will use it constantly for debugging.
Statements and comments
// A single-line comment
/* A multi-line
comment */
console.log("Each instruction is a statement");Practice
Create a page with a button that changes the heading text and logs a message to the console.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Print a message to the console and use alert once to see the difference.
- Add a script tag to a page and change a heading with JavaScript.
- Write what happens when you open the console and type 2 + 2.
Common mistakes
- Placing the script before the elements it uses.
- Mixing up Java and JavaScript, which are different languages.
Quick check
Where does JavaScript run in a browser?
In the browser's JavaScript engine, on the user's device.
How do you see console output?
In the browser developer tools.