JavaScript Tutorial · Chapter 4 of 8
JS Functions
Group reusable actions.
A function packages steps you want to reuse or attach to events.
Name functions with verbs such as sayHello or updateMessage.
Function sample
Try it Yourself »
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Functions</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Functions</h1>
<p id="message">Ready</p>
<button onclick="sayHello()">Greet</button>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
padding: 32px;
}
button {
padding: 10px 14px;
border: 0;
border-radius: 8px;
background: #0369a1;
color: white;
}
script.js
function sayHello() {
document.getElementById("message").textContent = "Hello, classmate!";
}
Classroom Tips
- Prefer addEventListener for larger projects.
- onclick is fine for very small demos.