It changes the page after it loads.
It can rewrite text, swap pictures, change colors, and add or remove whole sections of HTML and CSS.
JavaScript Tutorial for Beginners
HTML builds a page, and JavaScript makes it do things. With a few lines of code, a page can answer a click, check a form, keep time, or play a game.
This tutorial starts at the very beginning. It explains what JavaScript is, how it grew, how to spot an outdated book, and what the 30 most useful commands do. Along the way, you can click live examples and watch the code work.
let clicks = 0;
button.addEventListener("click", () => {
clicks++;
message.textContent =
`You clicked ${clicks} times.`;
});
The code is waiting for your click.
Part 1
JavaScript is a programming language that runs inside your web browser. HTML describes what is on a page, and CSS describes how it looks. JavaScript gives the page behavior. It can wait for something to happen, make a decision, and change the page in response, all without loading a new page.
JavaScript is not Java. The two languages share part of a name and almost nothing else. In 1995, Java was the exciting new language, and Netscape borrowed the name for marketing. A used book titled "Java" teaches a completely different language, so check the cover carefully.
JavaScript is a real programming language. HTML is a markup language that only labels content. JavaScript can calculate, remember values, repeat steps, and make decisions, just like the languages used to build any other software.
It can rewrite text, swap pictures, change colors, and add or remove whole sections of HTML and CSS.
It notices clicks, typing, scrolling, and mouse movement, and it runs code when they happen.
It can make sure a form is filled out correctly before it is sent to the server.
It creates animations and interactive graphics, including drawings on the HTML canvas.
It sends and receives data in the background, which is how weather and news update without reloading the page.
Calculators, games, dashboards, and even word processors run in the browser on JavaScript.
Part 2
JavaScript began as a small language for making buttons respond. Thirty years later, it is the most widely used programming language in the world. Here is how that happened.
Brendan Eich created the first version at Netscape in about ten days. It was called Mocha, then LiveScript, and finally JavaScript.
A standards group called Ecma International wrote down the official rules. That is why you see version names such as ES5 and ES6. "ES" stands for ECMAScript, which is the official name of the language.
Gmail and Google Maps showed that JavaScript could fetch new data without reloading the page. This technique was named AJAX, and it changed what people expected from the web.
Every browser behaved a little differently, and the jQuery library hid those differences. For years, many books taught jQuery more than JavaScript itself.
Google's Chrome browser arrived with a new engine named V8 that ran JavaScript many times faster. Other browsers raced to catch up.
Node.js let JavaScript run on servers and ordinary computers. The same year, ES5 cleaned up many old problems.
ES6, also called ECMAScript 2015, was the biggest change in the language's history. It added let and const, arrow functions, classes, template literals, promises, and modules. This is the dividing line between old and modern JavaScript.
Since 2016, the language has been updated every June with smaller improvements, such as async and await in 2017. Browsers now agree closely, so tools like jQuery are rarely needed.
Today JavaScript runs nearly everywhere. It runs in every web browser, on web servers through Node.js, in phone apps, and in desktop programs. Visual Studio Code, the editor many people use to write web pages, is itself built with JavaScript and its close relative, TypeScript.
Part 3
If your JavaScript book was published before 2016, it probably does not cover modern JavaScript, which is often called ES6 or ECMAScript 2015 and later. Modern JavaScript is cleaner and easier to read, especially for beginners. Before you buy a used book, make sure it is about JavaScript and not Java, and then check for the signs below.
var for every variable and never mentions let or const.document.write().$() function for nearly everything.XMLHttpRequest instead of fetch().language="JavaScript".let and const from the first chapter.x => x * 2.${}.fetch() with async and await.querySelector() and addEventListener().import and export.Old JavaScript still runs. Browsers keep supporting old code so that old websites do not break. An old book will not teach you anything that fails, but it will teach you the long way around. Use the free websites at the end of this page for the modern way.
Part 4
JavaScript goes inside a <script> tag in an HTML page. This first example writes a message to the browser console, which is a hidden window that programmers use to test their code.
<script> console.log("Hello, world!"); </script>
Press F12 in Chrome or Edge, and click the Console tab. Anything sent with console.log() appears there. Errors appear there in red, with the line number where the trouble is.
To show something to visitors, change an element on the page. This is how nearly all real JavaScript works.
message.textContent = "Hello!";
The alert() command opens a small box that the visitor must close. It is handy for testing, but visitors find it annoying on real pages.
Keep your JavaScript in its own file. Short scripts can sit inside the page, but larger ones belong in a separate file, such as script.js. Place this line just before the closing body tag. The defer word tells the browser to run the script after the page has loaded.
<script src="script.js" defer></script>
Part 5
These twelve ideas appear in almost every JavaScript program. Read them once for the big picture. The 30 commands in Part 6 show each idea in use.
A variable is a labeled box that holds a value. Use let when the value will change and const when it will not.
let score = 0; const name = "George";
A function is a named, reusable block of steps. You write it once and run it whenever you need it.
function greet(person) {
return "Hello, " + person;
}
An event is something that happens, such as a click, a key press, or the page finishing its load. Your code can listen for it.
button.addEventListener("click", greet);
The Document Object Model turns every HTML tag into an object that JavaScript can read and change. It is shaped like a family tree, with html at the top.
document.querySelector("h1").textContent = "New title";
An object holds several named values together, like a card in a file drawer. It can also hold functions.
const radio = { brand: "Flex", model: 5000, on: true };
An array is an ordered list. Each item has a position number, and counting starts at zero.
const colors = ["red", "green", "blue"]; colors[0]; // "red"
A conditional runs different code depending on whether something is true. The commands are if, else, and switch.
if (score > 10) { win(); } else { tryAgain(); }
A loop runs the same code many times. The common forms are for, while, and forEach.
for (let i = 1; i <= 3; i++) { console.log(i); }
A variable made inside a pair of curly braces exists only inside them. That is local scope. A variable made outside every function can be seen everywhere, which is global scope.
if (true) { let secret = 1; }
// secret does not exist out here.
A template literal uses backticks instead of quotation marks. Anything inside ${} is filled in with its value.
`You have ${score} points.`
An arrow function is a compact way to write a function, using =>. It is common in modern code.
const square = x => x * x;
A class describes a kind of object. You can then build as many objects from it as you like, each with its own values.
class Dog {
constructor(name) { this.name = name; }
}
const rex = new Dog("Rex");
Part 6
Programmers call these keywords, functions, and methods, but "commands" is a fine word for a beginner. They are grouped by the job they do. Each one has a plain description and a short example that you can copy.
These are the building blocks of every program.
These arrived with ES6 in 2015. Old books do not have them.
These commands reach into the HTML and change it.
These commands show messages and ask questions.
These commands work with values.
These commands wait, repeat, and fetch data.
Part 7
Each of these examples is running on this page right now. Press the buttons, and then read the code underneath to see exactly what happened.
This sentence is about to change.
const p = document.getElementById("demoText");
changeBtn.addEventListener("click", () => {
p.textContent = "JavaScript changed me!";
});const faces = ["⚀","⚁","⚂","⚃","⚄","⚅"];
rollBtn.addEventListener("click", () => {
const roll = Math.floor(Math.random() * 6);
dieFace.textContent = faces[roll];
});addBtn.addEventListener("click", () => {
const text = itemInput.value.trim();
if (text === "") return; // skip empty boxes
const li = document.createElement("li");
li.textContent = text;
shopList.append(li);
itemInput.value = "";
});function tick() {
clockFace.textContent =
new Date().toLocaleTimeString();
}
tick(); // show it now
let timer = setInterval(tick, 1000); // then every secondPart 8
These short pieces of code solve everyday problems. Each one has comments that explain what it does. Where a snippet needs a matching HTML tag or CSS rule, that is shown in a comment at the top.
alert("Welcome to my site!");// HTML: <p id="demo">Old Text</p>
document.getElementById("demo").innerText = "New Text";// If the box is hidden, show it. Otherwise, hide it.
const box = document.getElementById("box");
box.style.display = (box.style.display === "none") ? "block" : "none";// HTML: <button id="btn">Click Me</button>
document.getElementById("btn").addEventListener("click", () => {
alert("Button clicked!");
});// HTML: <input id="name">
const name = document.getElementById("name").value;
if (name === "") {
alert("Name is required");
}const now = new Date(); console.log(now.toString());
const colors = ["red", "green", "blue"]; colors.forEach(color => console.log(color));
// CSS: #fadeTarget { opacity: 0; transition: opacity 1s; }
// #fadeTarget.fade-in { opacity: 1; }
document.getElementById("fadeTarget").classList.add("fade-in");const user = prompt("What is your name?");
alert("Hello, " + user);const number = Math.floor(Math.random() * 10) + 1; console.log(number);
document.body.style.backgroundColor = "lightblue";
// HTML: <button id="clickMe">Click</button>
let count = 0;
document.getElementById("clickMe").onclick = () => {
count++;
console.log("Clicked " + count + " times");
};// HTML: <img id="myImg" src="old.jpg">
document.getElementById("myImg").src = "new.jpg";// HTML: <ul id="myList"></ul>
const ul = document.getElementById("myList");
const li = document.createElement("li");
li.textContent = "New item";
ul.appendChild(li);setTimeout(() => {
alert("Time's up!");
}, 3000);// HTML: <span id="clock"></span>
// Update the time now, and again every second.
const clock = document.getElementById("clock");
const showTime = () => clock.innerText = new Date().toLocaleTimeString();
showTime();
setInterval(showTime, 1000);// HTML: <div id="hoverMe">Point here</div>
document.getElementById("hoverMe").onmouseover = () => {
console.log("Mouse is over");
};window.onscroll = () => {
console.log("Scrolling...");
};const firstName = "Sam";
console.log(`Hello, ${firstName}!`);const square = x => x * x; console.log(square(4)); // 16
Part 9
A website usually shows the same navigation menu on every page. When you add a page, you want to change the menu in one place, not in every file. There are three ways to do it.
You paste the same menu HTML into each file. It is simple, but every change must be made in every file.
<nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="tutorial.html">Tutorial</a></li> <li><a href="contact.html">Contact</a></li> </ul> </nav>
You keep the menu in one file named menu.html. Each page has an empty placeholder, and fetch fills it in.
<div id="menu-placeholder"></div> <script> fetch("menu.html") .then(response => response.text()) .then(data => { document.getElementById("menu-placeholder") .innerHTML = data; }); </script>
You create menu.php and include it in each page. The server builds the finished page before sending it. Change the page file names from .html to .php.
<?php include 'menu.php'; ?>
Option 2 needs a web server to test. If you double-click a page to open it straight from your hard drive, the browser blocks fetch for safety, and the menu will not appear. Test it with the Live Server extension in VS Code, or on your real website, and it will work.
A search engine may also see the page before JavaScript adds the menu. Option 3 avoids that, because the server adds the menu before anyone sees the page.
Part 10
Comments are notes that JavaScript ignores when it runs. They explain the code to other people, and to yourself six months from now. When something goes wrong, the browser's developer tools help you find out why.
Everything after the slashes, to the end of the line, is ignored.
// This is a comment let total = 0; // Comments can follow code, too.
Everything between the opening and the closing marks is ignored.
/* This is a multi-line comment. It can go over many lines. */
Press F12 and open the Console tab. A red message names the error and the line number. Most beginner errors are a misspelled name, a missing parenthesis, or a missing quotation mark.
Part 11
You are now ready to build your own JavaScript programs. Copy the snippets into an HTML page inside a script tag, change them, and see what happens. These six steps make a good path forward.
Paste each snippet into a page, run it, and then change one thing at a time. Breaking code and fixing it is how everyone learns.
Put your JavaScript in script.js and load it with <script src="script.js" defer>. Your HTML stays tidy, and many pages can share the same code.
Press F12 to see the console, inspect any element on the page, and pause your code line by line to watch what it does.
A tip calculator, a quiz, or a to-do list will use most of the 30 commands. Finishing one small project teaches more than reading three chapters.
Use fetch with async and await to load information from another file or a public data service, and show it on your page.
React, Vue, and Svelte help teams build large web applications. Learn plain JavaScript first, because every framework is built on it.
Part 12
All of these sites teach modern JavaScript, and all of them can be used for free. If you only pick one, start with The Modern JavaScript Tutorial or the MDN course, and keep the MDN reference open while you work. If you have not learned HTML yet, start with the HTML5 tutorial first.
"HTML gives a page its body, and JavaScript gives it a pulse. Start small, try everything, and let the console tell you what went wrong."
DeepermindOpen a page, add a script tag, and type a single console.log. When your message appears in the console, you are a programmer.