JavaScript Tutorial · Chapter 3 of 8
JS Variables
Store values with let and const.
Use const when the binding should not be reassigned. Use let when the value can change.
Choose clear names such as clicks, message, and fullName.
Variables sample
Try it Yourself »
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Variables</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Variables</h1>
<p id="output">Click to count</p>
<button id="countButton">Count</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: #0f766e;
color: white;
}
script.js
let clicks = 0;
const output = document.getElementById("output");
document.getElementById("countButton").addEventListener("click", function () {
clicks += 1;
output.textContent = "Clicked " + clicks + " time(s).";
});
Classroom Tips
- Update the page with textContent.
- Avoid var in new beginner code when possible.