JavaScript Tutorial for Beginners

Make Your Pages Come Alive

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

What JavaScript Is

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.

What Can JavaScript Do?

✏️

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.

🖱️

It responds to people.

It notices clicks, typing, scrolling, and mouse movement, and it runs code when they happen.

✅

It checks forms.

It can make sure a form is filled out correctly before it is sent to the server.

🎞️

It animates.

It creates animations and interactive graphics, including drawings on the HTML canvas.

🔄

It talks to servers.

It sends and receives data in the background, which is how weather and news update without reloading the page.

🧮

It builds whole programs.

Calculators, games, dashboards, and even word processors run in the browser on JavaScript.

Part 2

What JavaScript Has Become

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.

  1. 1995
    A language is written in ten days.

    Brendan Eich created the first version at Netscape in about ten days. It was called Mocha, then LiveScript, and finally JavaScript.

  2. 1997
    It becomes a standard named ECMAScript.

    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.

  3. 2005
    Web pages start to feel like programs.

    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.

  4. 2006
    jQuery smooths over browser differences.

    Every browser behaved a little differently, and the jQuery library hid those differences. For years, many books taught jQuery more than JavaScript itself.

  5. 2008
    JavaScript becomes fast.

    Google's Chrome browser arrived with a new engine named V8 that ran JavaScript many times faster. Other browsers raced to catch up.

  6. 2009
    JavaScript leaves the browser.

    Node.js let JavaScript run on servers and ordinary computers. The same year, ES5 cleaned up many old problems.

  7. 2015
    Modern JavaScript arrives with ES6.

    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.

  8. 2016 on
    A new version arrives every year.

    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

How to Spot an Outdated JavaScript Book

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.

📕

Signs that a book is obsolete

  • It uses var for every variable and never mentions let or const.
  • It writes to the page with document.write().
  • It teaches jQuery and its $() function for nearly everything.
  • It fetches data with XMLHttpRequest instead of fetch().
  • It nests functions inside functions inside functions, a tangle known as "callback hell."
  • It has no arrow functions, no classes, and no template literals.
  • It spends pages on special code for Internet Explorer.
  • It hides scripts inside HTML comments or uses language="JavaScript".
📗

Signs that a book is up to date

  • The title or cover says ES6, ES2015, or "modern JavaScript."
  • It uses let and const from the first chapter.
  • It uses arrow functions such as x => x * 2.
  • It builds strings with backticks and ${}.
  • It teaches fetch() with async and await.
  • It uses querySelector() and addEventListener().
  • It covers modules with import and export.
  • It was published in 2016 or later.

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

Your First JavaScript

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>
🔧

The console shows messages to you.

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.

📄

The page shows results to visitors.

To show something to visitors, change an element on the page. This is how nearly all real JavaScript works.

message.textContent = "Hello!";
💬

A popup demands attention.

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

Twelve Ideas Behind Every Program

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.

📦 Variables store data.

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";

🧰 Functions group code.

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;
}

🔔 Events trigger code.

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 DOM is the page as JavaScript sees it.

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";

🗃️ Objects group related values.

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 };

📋 Arrays store lists.

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"

🔀 Conditionals make decisions.

A conditional runs different code depending on whether something is true. The commands are if, else, and switch.

if (score > 10) { win(); } else { tryAgain(); }

🔁 Loops repeat actions.

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); }

🔒 Scope decides who can see a variable.

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.

🧵 Template literals build strings.

A template literal uses backticks instead of quotation marks. Anything inside ${} is filled in with its value.

`You have ${score} points.`

➡️ Arrow functions are short functions.

An arrow function is a compact way to write a function, using =>. It is common in modern code.

const square = x => x * x;

🏭 Classes are blueprints.

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

The 30 Most Useful JavaScript Commands

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.

Storing values and making decisions

These are the building blocks of every program.

1
let
The let keyword creates a variable whose value can change later. Old code used var for the same job, but let is safer because it stays inside its own block.
let count = 0;
count = count + 1;
2
const
The const keyword creates a variable that will not be given a new value. Use it by default, and switch to let only when you need to change the value.
const taxRate = 0.0825;
3
if / else
The if command runs code only when a condition is true. The else part runs when it is false, and else if adds more choices.
if (temp > 90) {
  console.log("Water the garden.");
} else {
  console.log("The garden is fine.");
}
4
switch
The switch command picks one of many choices by matching a value. It is tidier than a long chain of else if lines.
switch (day) {
  case "Sunday": console.log("Church"); break;
  case "Monday": console.log("Radio club"); break;
  default: console.log("Free day");
}
5
for
The for loop repeats code a set number of times. It has three parts: a starting count, a condition to keep going, and a step that changes the count.
for (let i = 1; i <= 5; i++) {
  console.log("Line " + i);
}
6
while
The while loop repeats code as long as a condition stays true. Make sure something inside the loop eventually makes it false.
let fuel = 3;
while (fuel > 0) {
  fuel--;
}
7
function
The function keyword defines a named block of reusable code. The values in parentheses are inputs, called parameters.
function add(a, b) {
  return a + b;
}
8
return
The return command sends a result back from a function and ends the function right there.
const total = add(2, 3);  // total is 5

Modern shortcuts

These arrived with ES6 in 2015. Old books do not have them.

9
=> (arrow function)
An arrow function is a short way to write a function. If the body is one expression, you can leave out the braces and the word return.
const double = n => n * 2;
double(4);  // 8
10
`${ }` (template literal)
A template literal is a string written with backticks. Values inside ${} are filled in automatically, and the string can run over several lines.
const firstName = "Sam";
console.log(`Hello, ${firstName}!`);
11
class
The class keyword defines a blueprint for objects. The constructor sets up each new object, and the new keyword builds one.
class Station {
  constructor(freq) { this.freq = freq; }
  describe() { return `${this.freq} kHz`; }
}
const rwm = new Station(9996);

Finding and changing the page

These commands reach into the HTML and change it.

12
document.getElementById()
This command finds the one element whose id attribute matches the name you give.
// HTML: <p id="demo">Old text</p>
const demo = document.getElementById("demo");
13
querySelector() and querySelectorAll()
These commands find elements using the same selectors as CSS. The first returns the first match, and the second returns all matches as a list.
const title = document.querySelector("h1");
const cards = document.querySelectorAll(".card");
14
.textContent
The textContent property reads or replaces the plain text inside an element. It is the safe choice for showing words.
demo.textContent = "New text";
15
.innerHTML
The innerHTML property reads or replaces the HTML inside an element, tags and all. Never use it with text that visitors typed, because it can let harmful code into the page.
demo.innerHTML = "<strong>Bold</strong> text";
16
.style
The style property changes one CSS setting on one element. CSS names with hyphens become one word with a capital letter, so background-color becomes backgroundColor.
document.body.style.backgroundColor = "lightblue";
17
.classList
The classList property adds, removes, or toggles CSS classes. It is usually better than style, because the look stays in your CSS file.
menu.classList.add("open");
menu.classList.toggle("open");
18
createElement() and append()
These two commands work together. The first builds a new element, and the second places it inside another element on the page.
const li = document.createElement("li");
li.textContent = "New item";
myList.append(li);
19
addEventListener()
This command attaches a function to an element so that the function runs when an event happens, such as "click," "input," or "keydown."
btn.addEventListener("click", () => {
  alert("Button clicked!");
});

Talking with people

These commands show messages and ask questions.

20
console.log()
This command prints a message in the browser console. It is the programmer's best friend for checking what a variable holds.
console.log("count is", count);
21
alert()
This command shows a popup box with a message and an OK button. The page waits until the visitor closes it.
alert("Welcome to my site!");
22
prompt()
This command shows a popup box that asks the visitor to type something, and it returns what they typed.
const user = prompt("What is your name?");
alert(`Hello, ${user}`);

Numbers, dates, and lists

These commands work with values.

23
Math.random() and Math.floor()
Math.random gives a random decimal number from 0 up to, but not including, 1. Math.floor rounds down. Together they pick a random whole number.
// A random number from 1 to 6
const roll = Math.floor(Math.random() * 6) + 1;
24
new Date()
This command creates an object holding the current date and time. Its methods format the date or pull out one part of it.
const now = new Date();
now.toLocaleTimeString();  // "3:42:07 PM"
25
.push()
The push method adds an item to the end of an array.
const colors = ["red", "green"];
colors.push("blue");
26
.forEach()
The forEach method runs a function once for each item in an array. Its cousins map and filter build new arrays by changing or selecting items.
colors.forEach(color => console.log(color));
const big = [1, 5, 9].filter(n => n > 3);  // [5, 9]

Time and the Internet

These commands wait, repeat, and fetch data.

27
setTimeout()
This command runs code once after a delay. The delay is in milliseconds, so 3000 means three seconds.
setTimeout(() => {
  alert("Time's up!");
}, 3000);
28
setInterval()
This command runs code over and over with a fixed delay between runs. The clearInterval command stops it.
const timer = setInterval(tick, 1000);
clearInterval(timer);  // stop it
29
fetch()
This command asks a server for data, such as a file or the latest weather. The answer arrives a moment later, and JSON is the usual format for it.
fetch("menu.html")
  .then(response => response.text())
  .then(html => console.log(html));
30
async and await
These two words let you write code that waits for slow things, such as fetch, as if it ran in a straight line. The function must be marked async, and await pauses until the answer arrives.
async function loadMenu() {
  const response = await fetch("menu.html");
  const html = await response.text();
  console.log(html);
}

Part 7

Watch JavaScript Work

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.

Change the text on the page.

This sentence is about to change.

const p = document.getElementById("demoText");

changeBtn.addEventListener("click", () => {
  p.textContent = "JavaScript changed me!";
});

Roll a die.

🎲
const faces = ["⚀","⚁","⚂","⚃","⚄","⚅"];

rollBtn.addEventListener("click", () => {
  const roll = Math.floor(Math.random() * 6);
  dieFace.textContent = faces[roll];
});

Add an item to a list.

  • Basil
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 = "";
});

Run a live clock.

--:--:--
function tick() {
  clockFace.textContent =
    new Date().toLocaleTimeString();
}
tick();                              // show it now
let timer = setInterval(tick, 1000); // then every second

Part 8

Twenty Useful Snippets to Copy

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.

1Show a popup message.

alert("Welcome to my site!");

2Change the text of an element.

// HTML: <p id="demo">Old Text</p>
document.getElementById("demo").innerText = "New Text";

3Show or hide an element.

// If the box is hidden, show it. Otherwise, hide it.
const box = document.getElementById("box");
box.style.display = (box.style.display === "none") ? "block" : "none";

4Respond to a button click.

// HTML: <button id="btn">Click Me</button>
document.getElementById("btn").addEventListener("click", () => {
  alert("Button clicked!");
});

5Check that a form field is filled in.

// HTML: <input id="name">
const name = document.getElementById("name").value;
if (name === "") {
  alert("Name is required");
}

6Get the current date and time.

const now = new Date();
console.log(now.toString());

7Loop through a list.

const colors = ["red", "green", "blue"];
colors.forEach(color => console.log(color));

8Fade an element in.

// CSS: #fadeTarget { opacity: 0; transition: opacity 1s; }
//      #fadeTarget.fade-in { opacity: 1; }
document.getElementById("fadeTarget").classList.add("fade-in");

9Ask the visitor a question.

const user = prompt("What is your name?");
alert("Hello, " + user);

10Pick a random number from 1 to 10.

const number = Math.floor(Math.random() * 10) + 1;
console.log(number);

11Change the page background color.

document.body.style.backgroundColor = "lightblue";

12Count clicks on a button.

// HTML: <button id="clickMe">Click</button>
let count = 0;
document.getElementById("clickMe").onclick = () => {
  count++;
  console.log("Clicked " + count + " times");
};

13Swap a picture.

// HTML: <img id="myImg" src="old.jpg">
document.getElementById("myImg").src = "new.jpg";

14Add an item to a list.

// HTML: <ul id="myList"></ul>
const ul = document.getElementById("myList");
const li = document.createElement("li");
li.textContent = "New item";
ul.appendChild(li);

15Wait three seconds, then act.

setTimeout(() => {
  alert("Time's up!");
}, 3000);

16Keep a clock running.

// 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);

17React when the mouse moves over something.

// HTML: <div id="hoverMe">Point here</div>
document.getElementById("hoverMe").onmouseover = () => {
  console.log("Mouse is over");
};

18React when the page scrolls.

window.onscroll = () => {
  console.log("Scrolling...");
};

19Fill in a string with a template literal.

const firstName = "Sam";
console.log(`Hello, ${firstName}!`);

20Write a one-line arrow function.

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.

Option 1: Copy it by hand.

This works best for a small site with a few pages.

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>

Option 2: Load it with JavaScript.

This works on basic hosting without PHP.

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>

Option 3: Include it with PHP.

This works on hosting that supports PHP.

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 and Finding Mistakes

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.

💬

A single-line comment starts with two slashes.

Everything after the slashes, to the end of the line, is ignored.

// This is a comment
let total = 0;  // Comments can follow code, too.
📝

A multi-line comment uses slash and star.

Everything between the opening and the closing marks is ignored.

/*
  This is a multi-line comment.
  It can go over many lines.
*/
🐞

The console tells you what went wrong.

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

Where to Go from Here

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.

1🧪

Experiment with the snippets.

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.

2📂

Move your code into a file.

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.

3🔧

Learn the developer tools.

Press F12 to see the console, inspect any element on the page, and pause your code line by line to watch what it does.

4🛠️

Build something small.

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.

5🌐

Fetch real data.

Use fetch with async and await to load information from another file or a public data service, and show it on your page.

6🚀

Look at frameworks later.

React, Vue, and Svelte help teams build large web applications. Learn plain JavaScript first, because every framework is built on it.

Part 12

The Best Websites for Learning JavaScript

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."

Deepermind

Your First Program Is One Line Away

Open a page, add a script tag, and type a single console.log. When your message appears in the console, you are a programmer.