JavaScript is the language of the web. Every browser runs it, which makes it the only language that can make a web page interactive: menus that open, forms that check themselves, content that updates without reloading, games, charts, maps and complete applications such as Gmail or Google Docs. With Node.js it also runs on servers, and it is used for mobile apps, desktop apps, command-line tools and automation. If HTML is the structure of a page and CSS its looks, JavaScript is its behaviour.
This tutorial takes you from the first line of code to a working interactive application. It explains why things work as they do, including the famous oddities of the language. Every example was executed in a real browser engine before publishing, and the results shown in comments are the real results. It is the third in a series with our HTML tutorial and CSS tutorial, and it uses the same ideas as the Python and C# tutorials, so you can compare languages as you go.
Contents
- 1. Running JavaScript
- 2. Variables, types and operators
- 3. Strings and numbers
- 4. Decisions and loops
- 5. Functions
- 6. Arrays
- 7. Objects, JSON, Map and Set
- 8. Classes and modules
- 9. Errors
- 10. The DOM: changing the page
- 11. Events and forms
- 12. Asynchronous JavaScript: timers, promises, async/await and fetch
- 13. Remembering data: localStorage
- 14. Node.js, npm and modern tooling
- 15. Security basics
- 16. Project: a to-do application
- 17. Common mistakes and FAQ
1. Running JavaScript
You can try JavaScript right now, without installing anything. In any browser press F12, open the Console tab, type 2 + 2 and press Enter. Experiment there as you read. To put JavaScript in a web page, add a <script> element, preferably in an external file loaded with defer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS test</title>
<script src="app.js" defer></script> <!-- defer: run after the HTML has been read -->
</head>
<body>
<h1 id="title">Hello</h1>
</body>
</html>
// app.js
console.log("Hello from JavaScript!"); // appears in the Console panel
document.getElementById("title").textContent = "Hello, JavaScript!";
Outside a browser, install Node.js (nodejs.org, or winget install OpenJS.NodeJS.LTS, sudo dnf install nodejs) and run a file with node app.js. Everything in sections 2 to 9 works the same in the browser and in Node; the DOM sections (10 to 13) are browser-only. console.log() prints values; you will use it all the time. Comments are written // like this or /* over several lines */. Statements end with a semicolon, which is optional but recommended.
2. Variables, types and operators
Declare variables with let (can be reassigned) or const (cannot be reassigned). Use const by default, and let only when the value must change. Avoid the old var: it has confusing scoping rules.
const name = "Sara"; // a string
let age = 31; // a number
let isAdmin = true; // a boolean
let nothing = null; // "no value", set on purpose
let notSet; // undefined: a variable that was never given a value
age = age + 1; // fine with let
console.log(name, age, isAdmin, nothing, notSet); // Sara 32 true null undefined
try {
name = "Omar"; // not allowed with const
} catch (error) {
console.log(error.name + ": " + error.message); // TypeError: Assignment to constant variable.
}
console.log(typeof "text", typeof 42, typeof true, typeof undefined, typeof null, typeof {}, typeof [], typeof (() => 1));
// string number boolean undefined object object object function (typeof null is "object": a famous old bug)
The basic (primitive) types are number, string, boolean, null, undefined, bigint and symbol. Everything else is an object (arrays, functions, dates, and your own objects). JavaScript is dynamically typed: a variable can hold any type, and the type belongs to the value.
Operators, equality and truthiness
console.log(7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 % 3, 2 ** 10); // 9 5 14 3.5 1 1024
// ALWAYS use === (strict equality). == converts types first and gives odd answers.
console.log(5 === "5", 5 == "5", 0 == false, null == undefined, null === undefined); // false true true true false
console.log("5" + 3, "5" - 3, "5" * "2", [] + [], true + 1); // 53 2 10 (empty) 2 - + joins text if either side is text
// Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy (including "0", [] and {}).
console.log(Boolean(""), Boolean("0"), Boolean([]), Boolean(0), Boolean(NaN)); // false true true false false
const user = { profile: { city: "Tangier" } };
console.log(user.profile?.city, user.settings?.theme, user.settings?.theme ?? "light"); // Tangier undefined light
// ?. stops safely when something is null/undefined ?? gives a default only for null or undefined
let count = 0;
count ||= 10; // assigns if count is falsy: 0 is falsy, so count becomes 10
let label = "";
label ??= "none"; // assigns only if null or undefined: "" is NOT nullish, so label stays empty
console.log(count, JSON.stringify(label)); // 10 ""
Rule: use === and !==, and use ?? (not ||) for defaults when 0 or an empty string are valid values.
3. Strings and numbers
const s = "JavaScript is fun";
console.log(s.length, s[0], s.at(-1), s.slice(0, 10), s.slice(-3)); // 17 J n JavaScript fun
console.log(s.toUpperCase(), s.includes("is"), s.startsWith("Java"), s.indexOf("fun")); // JAVASCRIPT IS FUN true true 14
console.log(s.replace("fun", "great"), " trim me ".trim() + "|", "a,b,c".split(","), ["x", "y"].join("-"));
// JavaScript is great trim me| [ 'a', 'b', 'c' ] x-y
console.log("ha".repeat(3), "7".padStart(3, "0"), "abc".replaceAll("b", "-")); // hahaha 007 a-c
const item = "Tea", price = 3.5, qty = 4;
console.log(`${item} costs ${price} each; total ${(price * qty).toFixed(2)}`); // Tea costs 3.5 each; total 14.00
console.log(`line one
line two`); // template literals (backticks) can span lines and embed expressions
console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // 0.30000000000000004 false true
console.log(Number("42"), Number("abc"), parseInt("42px"), parseFloat("3.14abc"), Number.isNaN(NaN), NaN === NaN); // 42 NaN 42 3.14 true false
console.log(Math.round(2.5), Math.floor(-2.5), Math.ceil(2.1), Math.max(3, 9, 4), Math.min(...[3, 9, 4]), Math.trunc(-2.7)); // 3 -3 3 9 3 -2
console.log((1234567.891).toLocaleString("en-US"), (0.256).toLocaleString("en-US", { style: "percent" }), Number.MAX_SAFE_INTEGER);
// 1,234,567.891 26% 9007199254740991
console.log(Math.floor(Math.random() * 6) + 1 >= 1, 10n ** 20n); // true 100000000000000000000n (bigint for huge integers)
JavaScript has a single number type (a 64-bit float), so the same decimal surprises appear as in other languages (0.1 + 0.2). For money, count in whole cents or use a library. NaN (“not a number”) is the result of a failed calculation, and it is the only value not equal to itself: test it with Number.isNaN().
4. Decisions and loops
const temperature = 22;
if (temperature > 30) {
console.log("hot");
} else if (temperature > 18) {
console.log("pleasant"); // pleasant
} else {
console.log("cold");
}
console.log(temperature > 20 ? "warm" : "cool"); // warm (the ternary operator)
const day = "sat";
switch (day) {
case "sat":
case "sun":
console.log("weekend"); // weekend
break; // without break, execution falls through to the next case!
default:
console.log("weekday");
}
for (let i = 0; i < 3; i++) console.log("round", i); // round 0 / round 1 / round 2
for (const letter of "abc") console.log(letter); // a b c (for...of goes through VALUES of arrays, strings, Maps and Sets)
const prices = { tea: 3.5, coffee: 4 };
for (const key in prices) console.log(key, prices[key]); // tea 3.5 / coffee 4 (for...in goes through the KEYS of an object)
for (const [key, value] of Object.entries(prices)) console.log(`${key}=${value}`); // tea=3.5 / coffee=4
let n = 0;
while (n < 3) n++;
do { n--; } while (n > 0);
console.log(n); // 0
outer: for (let a = 0; a < 3; a++) {
for (let b = 0; b < 3; b++) {
if (b === 2) continue; // skip this inner round
if (a === 2) break outer; // leave BOTH loops
console.log(a, b); // 0 0 / 0 1 / 1 0 / 1 1
}
}
Use for...of for arrays and Object.entries() for objects. Avoid for...in on arrays: it gives the indexes as text, and may include unexpected inherited properties.
5. Functions
A function is a reusable block of code. In JavaScript, functions are values: you can store them in variables, pass them to other functions and return them. That one idea powers most of the language.
function add(a, b) { // a function declaration
return a + b;
}
const multiply = function (a, b) { return a * b; }; // a function expression
const square = (x) => x * x; // an arrow function: the modern short form
const greet = (name = "friend", greeting = "Hello") => `${greeting}, ${name}!`; // default values
console.log(add(2, 3), multiply(4, 5), square(6)); // 5 20 36
console.log(greet(), greet("Sara", "Salam")); // Hello, friend! Salam, Sara!
const sum = (...numbers) => numbers.reduce((total, n) => total + n, 0); // ...rest collects arguments in an array
console.log(sum(1, 2, 3, 4), sum(...[5, 6])); // 10 11 (... spreads an array into arguments)
function describe({ name, age = 0 }, ...tags) { // destructuring right in the parameters
return `${name} (${age}) [${tags.join(", ")}]`;
}
console.log(describe({ name: "Omar", age: 25 }, "admin", "dev")); // Omar (25) [admin, dev]
Scope and closures
let and const live inside the nearest { } block. A closure is a function that remembers the variables of the place where it was created, even after that place has finished. Closures give you private state and are the foundation of callbacks and event handlers.
function makeCounter() {
let count = 0; // private: nothing outside can touch it directly
return {
increment: () => ++count,
value: () => count,
};
}
const counter = makeCounter();
counter.increment(); counter.increment();
console.log(counter.value()); // 2
console.log(typeof count); // undefined (count is not visible out here)
const makeMultiplier = (factor) => (n) => n * factor; // a function that returns a function
const double = makeMultiplier(2), triple = makeMultiplier(3);
console.log(double(10), triple(10)); // 20 30
const delays = [];
for (var i = 0; i < 3; i++) delays.push(() => i); // the classic var trap: all closures share ONE i
console.log(delays.map(f => f())); // [ 3, 3, 3 ]
const fixed = [];
for (let j = 0; j < 3; j++) fixed.push(() => j); // with let, each round gets its own j
console.log(fixed.map(f => f())); // [ 0, 1, 2 ]
Callbacks and higher-order functions
function repeat(times, action) { // a higher-order function: it takes a function as an argument
for (let i = 0; i < times; i++) action(i);
}
repeat(3, (i) => console.log("step", i)); // step 0 / step 1 / step 2
// A function can also return a decorated version of another one
function logged(fn) {
return (...args) => {
const result = fn(...args);
console.log(`${fn.name}(${args.join(", ")}) = ${result}`);
return result;
};
}
const loggedAdd = logged(function add(a, b) { return a + b; });
loggedAdd(2, 3); // add(2, 3) = 5
About this: inside a regular function this depends on how the function is called; inside an arrow function it is inherited from the surrounding code. When you meet this problems (usually in object methods and event handlers), the rule of thumb is: use arrow functions for callbacks, and normal methods on classes and objects.
6. Arrays
An array is an ordered list. Learn these methods well: they replace most loops and are used everywhere in modern JavaScript.
const fruits = ["apple", "banana", "cherry"];
fruits.push("date"); // add at the end
fruits.unshift("avocado"); // add at the start
const last = fruits.pop(); // remove from the end
console.log(fruits, last, fruits.length); // [ 'avocado', 'apple', 'banana', 'cherry' ] date 4
console.log(fruits[0], fruits.at(-1), fruits.indexOf("banana"), fruits.includes("kiwi")); // avocado cherry 2 false
console.log(fruits.slice(1, 3), fruits.join(" | ")); // [ 'apple', 'banana' ] avocado | apple | banana | cherry
const numbers = [5, 2, 9, 1, 7];
console.log(numbers.map(n => n * 2)); // [ 10, 4, 18, 2, 14 ] transform every item
console.log(numbers.filter(n => n > 4)); // [ 5, 9, 7 ] keep the items that pass the test
console.log(numbers.reduce((total, n) => total + n, 0)); // 24 fold everything into one value
console.log(numbers.find(n => n > 5), numbers.findIndex(n => n > 5), numbers.some(n => n > 8), numbers.every(n => n > 0)); // 9 2 true true
// sort() changes the array and sorts as TEXT unless you give a compare function!
console.log([10, 9, 1, 100].sort()); // [ 1, 10, 100, 9 ] (as text: a classic bug)
console.log([10, 9, 1, 100].sort((a, b) => a - b)); // [ 1, 9, 10, 100 ]
console.log([...numbers].sort((a, b) => b - a), numbers); // [ 9, 7, 5, 2, 1 ] [ 5, 2, 9, 1, 7 ] copy first with [...array] to keep the original
console.log(numbers.toSorted((a, b) => a - b), numbers); // [ 1, 2, 5, 7, 9 ] [ 5, 2, 9, 1, 7 ] toSorted() returns a copy (modern engines)
console.log([[1, 2], [3, [4]]].flat(2), [1, 2, 3].flatMap(n => [n, n * 10])); // [ 1, 2, 3, 4 ] [ 1, 10, 2, 20, 3, 30 ]
console.log(Array.from({ length: 5 }, (_, i) => i * i), Array(3).fill(0), [..."abc"]); // [ 0, 1, 4, 9, 16 ] [ 0, 0, 0 ] [ 'a', 'b', 'c' ]
const [first, second, ...others] = [10, 20, 30, 40]; // destructuring
console.log(first, second, others); // 10 20 [ 30, 40 ]
const copy = [...numbers, 100]; // spread builds a new array
const people = [{ name: "Ann", age: 31 }, { name: "Bob", age: 25 }, { name: "Cy", age: 40 }];
console.log(people.filter(p => p.age > 28).map(p => p.name)); // [ 'Ann', 'Cy' ]
console.log(Object.groupBy(people, p => p.age > 30 ? "over30" : "under30"));
// { over30: [ { name: 'Ann', age: 31 }, { name: 'Cy', age: 40 } ], under30: [ { name: 'Bob', age: 25 } ] } (groups appear in the order they are first met)
(toSorted() and Object.groupBy() need a browser or Node version from 2023 or later.) map, filter and reduce do not change the original array; they return new values. Chain them to build a data pipeline: people.filter(...).map(...).sort(...). Methods such as push, pop, splice, sort and reverse do change the array in place.
7. Objects, JSON, Map and Set
An object is a collection of named values (properties) and functions (methods). It is JavaScript’s most important data structure.
const person = {
name: "Sara",
age: 31,
skills: ["html", "css"],
address: { city: "Tangier", country: "Morocco" },
greet() { return `Hi, I am ${this.name}`; }, // a method
};
person.email = "sara@example.com"; // add a property
delete person.age; // remove one
console.log(person.name, person["name"], person.address.city, person.greet()); // Sara Sara Tangier Hi, I am Sara
console.log(Object.keys(person), "age" in person, person.hasOwnProperty("name")); // [ 'name', 'skills', 'address', 'greet', 'email' ] false true
const key = "color";
const car = { make: "Fiat", [key]: "red" }; // a computed property name
const { make, color: paint, year = 2024 } = car; // destructuring with a rename and a default
console.log(make, paint, year); // Fiat red 2024
const base = { a: 1, b: 2 };
const merged = { ...base, b: 20, c: 30 }; // spread: copy and override
console.log(merged, Object.entries(merged).map(([k, v]) => `${k}=${v}`).join("&")); // { a: 1, b: 20, c: 30 } a=1&b=20&c=30
const nested = { list: [1, 2], info: { x: 1 } };
const shallow = { ...nested }; // shallow copy: nested objects are SHARED
shallow.info.x = 99;
console.log(nested.info.x); // 99
const deep = structuredClone(nested); // a real deep copy
deep.info.x = 5;
console.log(nested.info.x, deep.info.x); // 99 5
const frozen = Object.freeze({ id: 1 });
frozen.id = 2; // silently ignored (an error in strict mode)
console.log(frozen.id); // 1
Objects and arrays are reference types: const copy = original does not copy, it gives a second name to the same object. That is why const arrays can still be changed with push: const only stops you from re-assigning the variable.
JSON
const data = { name: "Sara", skills: ["html", "css"], active: true, manager: null, note: undefined, since: new Date("2026-10-30T10:00:00Z") };
const text = JSON.stringify(data);
console.log(text); // {"name":"Sara","skills":["html","css"],"active":true,"manager":null,"since":"2026-10-30T10:00:00.000Z"}
console.log(JSON.stringify({ a: 1, b: [1, 2] }, null, 2)); // pretty printed with 2 spaces
const back = JSON.parse(text);
console.log(back.skills[1], typeof back.since); // css string (dates become text: convert them yourself)
try { JSON.parse("{ bad json }"); }
catch (e) { console.log(e.name); } // SyntaxError
JSON is the text format that web servers and JavaScript use to exchange data. JSON.stringify drops undefined and functions, and always wrap JSON.parse in try/catch when the text comes from outside.
Map and Set
const scores = new Map([["Ann", 90], ["Bob", 72]]); // keys of any type, remembers insertion order
scores.set("Cy", 85);
console.log(scores.get("Bob"), scores.has("Dan"), scores.size, [...scores.keys()]); // 72 false 3 [ 'Ann', 'Bob', 'Cy' ]
for (const [name, score] of scores) console.log(name, score);
const unique = new Set([3, 1, 3, 2, 1]); // each value only once
console.log(unique.size, [...unique], unique.has(2)); // 3 [ 3, 1, 2 ] true
console.log([...new Set("mississippi")].join("")); // misp (the quick way to remove duplicates)
Dates
const d = new Date(Date.UTC(2026, 9, 30, 14, 30)); // months count from 0: 9 is October
console.log(d.toISOString(), d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDay()); // 2026-10-30T14:30:00.000Z 2026 10 5
console.log(new Intl.DateTimeFormat("en-GB", { dateStyle: "full", timeZone: "UTC" }).format(d)); // Friday, 30 October 2026
const inAWeek = new Date(d.getTime() + 7 * 24 * 60 * 60 * 1000);
console.log(inAWeek.toISOString().slice(0, 10), Math.round((inAWeek - d) / 86400000)); // 2026-11-06 7
Dates are awkward in JavaScript: months start at 0, and local time zones cause confusion. Store and send dates as ISO text in UTC, and format with Intl.DateTimeFormat. A new built-in, Temporal, is arriving to replace Date.
8. Classes and modules
class Account {
#balance = 0; // a private field (the # makes it truly private)
static count = 0; // belongs to the class, not to each object
constructor(owner, balance = 0) {
this.owner = owner;
this.#balance = balance;
Account.count++;
}
deposit(amount) {
if (amount <= 0) throw new RangeError("amount must be positive");
this.#balance += amount;
return this; // returning "this" allows chaining
}
get balance() { return this.#balance; } // a getter: read like a property
toString() { return `${this.owner}: ${this.#balance}`; }
}
class SavingsAccount extends Account { // inheritance
constructor(owner, balance, rate) {
super(owner, balance); // call the parent's constructor first
this.rate = rate;
}
addInterest() { return this.deposit(this.balance * this.rate); }
toString() { return "Savings - " + super.toString(); }
}
const a = new Account("Omar", 100).deposit(50);
const s = new SavingsAccount("Lina", 1000, 0.05).addInterest();
console.log(String(a), "|", String(s), "|", Account.count, s instanceof Account); // Omar: 150 | Savings - Lina: 1050 | 2 true
try { a.deposit(-5); } catch (e) { console.log(e.name + ": " + e.message); } // RangeError: amount must be positive
console.log(a.balance, a.balance = 5, a.balance); // 150 5 150 (assigning to a getter-only property is ignored)
JavaScript classes are a tidier way to write objects and prototypes. Many JavaScript programs use plain functions and objects instead of classes; use classes when you have things with state and behaviour together.
Modules
Split a program into files with ES modules. Each file has its own scope, and shares only what it exports:
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }
// main.js
import Calculator, { add, PI } from "./math.js";
import * as math from "./math.js"; // everything under one name
<!-- in the HTML page -->
<script type="module" src="main.js"></script>
Modules run in strict mode, are deferred by default, and need a web server (not file://) because of browser security rules. In Node, use the .mjs extension or set "type": "module" in package.json.
9. Errors
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function parseAge(text) {
const age = Number(text);
if (!Number.isInteger(age)) throw new ValidationError("age", `"${text}" is not a whole number`);
if (age < 0 || age > 150) throw new ValidationError("age", "age must be between 0 and 150");
return age;
}
for (const input of ["31", "abc", "200"]) {
try {
console.log("ok:", parseAge(input));
} catch (error) {
if (error instanceof ValidationError) console.log(`${error.name} in ${error.field}: ${error.message}`);
else throw error; // not ours: do not hide it
} finally {
console.log("checked", input); // runs every time
}
}
// ok: 31 / checked 31 / ValidationError in age: "abc" is not a whole number / checked abc / ValidationError in age: age must be between 0 and 150 / checked 200
try { undefinedFunction(); } catch (e) { console.log(e.name, "-", e.message); } // ReferenceError - undefinedFunction is not defined
try { null.length; } catch (e) { console.log(e.name); } // TypeError
Read error messages: the type (ReferenceError, TypeError, SyntaxError…), the message, and the file and line in the stack trace. In the browser, uncaught errors appear in red in the Console. The two most common are “Cannot read properties of undefined” (you used a value that does not exist yet: check it, or use ?.) and “x is not a function” (a typing mistake, or the value is not what you thought).
10. The DOM: changing the page
When the browser loads an HTML page, it builds a tree of objects called the DOM (Document Object Model). JavaScript can read and change that tree, and the page updates immediately. The global document is the entry point.
<!DOCTYPE html>
<html lang="en">
<body>
<h1 id="title">Original title</h1>
<ul id="list"><li>One</li><li>Two</li></ul>
<p class="note">A note</p>
<script>
const title = document.querySelector("#title"); // find ONE element with a CSS selector
const items = document.querySelectorAll("#list li"); // find ALL matches (a list)
const note = document.querySelector(".note");
title.textContent = "New title"; // change text (safe)
note.classList.add("highlight"); // add a CSS class
note.setAttribute("data-state", "ready"); // set an attribute
note.style.color = "crimson"; // an inline style (prefer classes)
const li = document.createElement("li"); // create an element
li.textContent = "Three";
document.querySelector("#list").appendChild(li); // add it to the page
items[0].remove(); // remove an element
document.title = "Page " + document.querySelectorAll("#list li").length;
</script>
</body>
</html>
Important points: querySelector takes any CSS selector ("#id", ".class", "nav a") and returns the first match or null; querySelectorAll returns every match. Use textContent to put text into an element. Use innerHTML only with HTML you wrote yourself: if it contains text from a user, it can run malicious scripts (section 15). Change looks by adding and removing classes (classList.add, remove, toggle) and keep the styling itself in CSS. To make sure the elements exist before the script runs, load it with defer or place it at the end of the body.
element.textContent = "plain text"; // safe
element.innerHTML = "<b>bold</b>"; // parses HTML: dangerous with untrusted text
element.classList.toggle("open"); // add if missing, remove if present
element.getAttribute("href"); element.dataset.productId; // data-product-id
parent.append(child); parent.prepend(child); element.replaceWith(other);
element.closest(".card"); // the nearest ancestor that matches
element.matches(".active"); element.contains(other);
element.getBoundingClientRect(); // size and position on screen
11. Events and forms
An event is something that happens: a click, a key press, a form submission, the page finishing loading. You attach a function (an event handler) with addEventListener, and the browser calls it when the event happens. This is the heart of interactive pages.
<!DOCTYPE html>
<html lang="en">
<body>
<button id="plus" type="button">+1</button>
<span id="value" aria-live="polite">0</span>
<form id="signup">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<button type="submit">Join</button>
<p id="message" role="status"></p>
</form>
<ul id="menu"><li><a href="#a" data-id="1">First</a></li><li><a href="#b" data-id="2">Second</a></li></ul>
<p id="clicked"></p>
<script>
let count = 0;
document.querySelector("#plus").addEventListener("click", () => {
count++;
document.querySelector("#value").textContent = count;
});
document.querySelector("#signup").addEventListener("submit", (event) => {
event.preventDefault(); // stop the browser from sending the form and reloading
const email = new FormData(event.target).get("email").trim();
document.querySelector("#message").textContent =
email.endsWith("@example.com") ? "Welcome, " + email : "Please use your example.com address";
});
// Event delegation: ONE listener on the parent handles clicks on all its children, even ones added later
document.querySelector("#menu").addEventListener("click", (event) => {
const link = event.target.closest("a");
if (!link) return;
event.preventDefault();
document.querySelector("#clicked").textContent = "You chose item " + link.dataset.id;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") document.querySelector("#clicked").textContent = "Escape pressed";
});
</script>
</body>
</html>
The handler receives an event object: event.target is the element that was clicked, event.preventDefault() cancels the default action (following a link, submitting a form), and event.key says which key was pressed. Other events you will use: input (every keystroke in a field), change, focus and blur, DOMContentLoaded, scroll, resize, mouseover, touchstart. Remove a listener with removeEventListener, or pass { once: true } for a one-time handler.
Event delegation (listening on the parent) is the professional way to handle lists, tables and menus whose items change. Forms: always use real <form>, <label> and <button type="submit"> elements (see the HTML tutorial), so that keyboard and screen-reader users are served. Check input in JavaScript for a better experience, and again on the server for security.
12. Asynchronous JavaScript: timers, promises, async/await and fetch
JavaScript runs your code on one thread, one thing at a time. A slow operation such as a network request must not freeze the page, so the browser performs it in the background and calls you back when it is done. Understanding the order is the key to async code:
console.log("1: start");
setTimeout(() => console.log("4: timer (a task, runs after the current code)"), 0);
Promise.resolve().then(() => console.log("3: promise (a microtask, runs right after the current code)"));
console.log("2: end of the main code");
// 1: start / 2: end of the main code / 3: promise... / 4: timer...
The event loop runs the main code to the end, then all pending microtasks (promise callbacks), then the next task (a timer, a click). That is why even a timer of 0 milliseconds runs after the promise. Never write code that depends on the exact timing of a timer.
Callbacks, promises and async/await
Old code uses nested callbacks, which becomes unreadable (“callback hell”). A Promise represents a value that will arrive later: it ends up fulfilled (with a result) or rejected (with an error). async/await lets you write promise-based code as if it ran top to bottom.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error("server unavailable")), ms));
// The promise style
wait(20, "A").then((v) => { console.log("then:", v); return wait(5, v + "B"); }).then((v) => console.log("chained:", v));
async function main() {
const a = await wait(80, "one"); // pauses THIS function, not the whole page
console.log("await:", a);
// Run things at the same time, and wait for all of them
const started = Date.now();
const results = await Promise.all([wait(100, "x"), wait(80, "y"), wait(60, "z")]);
console.log(results, Date.now() - started < 180); // [ 'x', 'y', 'z' ] true (about 100 ms in total, not 240)
// The first to finish wins
console.log(await Promise.race([wait(50, "slow"), wait(10, "fast")])); // fast
// Errors: await turns a rejection into a normal exception
try { await fail(10); }
catch (error) { console.log("caught:", error.message); } // caught: server unavailable
const settled = await Promise.allSettled([wait(5, "ok"), fail(5)]); // never throws: reports every outcome
console.log(settled.map((r) => r.status)); // [ 'fulfilled', 'rejected' ]
}
main();
Rules: await only works inside an async function (or at the top level of a module); an async function always returns a promise; start independent tasks together and await Promise.all(...) instead of awaiting them one after another; and always handle errors with try/catch (or .catch()): an unhandled rejection is a silent bug.
fetch: talking to servers
fetch sends HTTP requests from the browser (and from Node 18+). This code needs the internet and a server, so it is shown but not executed here:
async function loadUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) { // fetch does NOT throw for 404 or 500: check ok yourself
throw new Error(`HTTP ${response.status}`);
}
return response.json(); // parse the body as JSON (also a promise)
}
async function saveUser(user) {
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
loadUser(42)
.then((user) => { document.querySelector("#name").textContent = user.name; })
.catch((error) => { document.querySelector("#error").textContent = "Could not load: " + error.message; });
// Cancel a slow request
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
fetch("https://api.example.com/slow", { signal: controller.signal });
Browsers block requests to another website unless that server allows it with CORS headers; that is a security feature, and the fix is on the server. Never put passwords or API secrets in JavaScript that runs in the browser: anyone can read them. For the server side of an API, see our C# web API and Python tutorials.
Timers
const id = setInterval(() => console.log("tick"), 1000); // every second
setTimeout(() => clearInterval(id), 5000); // stop it after 5 seconds
requestAnimationFrame(function frame() { /* draw */ requestAnimationFrame(frame); }); // smooth animations
13. Remembering data: localStorage
Browsers can store small pieces of text for your site. localStorage keeps data until it is deleted; sessionStorage until the tab is closed. Store objects as JSON.
<!DOCTYPE html>
<html lang="en">
<body>
<p id="out"></p>
<script>
const KEY = "preferences";
const defaults = { theme: "light", fontSize: 16 };
function load() {
try { return { ...defaults, ...JSON.parse(localStorage.getItem(KEY) ?? "{}") }; }
catch { return { ...defaults }; } // corrupted data: fall back to the defaults
}
function save(prefs) { localStorage.setItem(KEY, JSON.stringify(prefs)); }
const prefs = load(); // first visit: the defaults
prefs.theme = "dark";
save(prefs);
document.querySelector("#out").textContent = JSON.stringify(load()); // {"theme":"dark","fontSize":16}
localStorage.removeItem(KEY); // and localStorage.clear() removes everything
</script>
</body>
</html>
Limits: about 5 MB per site, text only, and visitors (or their browser settings) can erase it, so never rely on it for important data. Do not store sensitive information in it (passwords, tokens that give access): any script on your page can read it. Wrap access in try/catch, because it can be blocked in private windows.
14. Node.js, npm and modern tooling
Node.js runs JavaScript outside the browser: servers, tools, build scripts. npm (installed with it) is the package manager, with more than two million free packages.
node --version # check the installation
node app.js # run a file
node # a REPL, like the browser console
npm init -y # create package.json (the description of your project)
npm install express # add a package (saved in package.json, files in node_modules)
npm install --save-dev vitest # a tool used only during development
npm run test # run a script defined in package.json
npx create-vite@latest my-app # create a new front-end project with the Vite build tool
// A tiny web server with only Node's built-in modules (server.js)
import { createServer } from "node:http";
createServer((request, response) => {
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify({ message: "Hello from Node", url: request.url }));
}).listen(3000, () => console.log("Listening on http://localhost:3000"));
Beyond the basics, the usual toolbox is: Vite (a fast development server and bundler), ESLint (finds bugs and enforces style), Prettier (formats code), Vitest or Jest (tests), and TypeScript, a superset of JavaScript that adds types and catches many mistakes before the code runs. After you are comfortable with JavaScript, TypeScript is the most valuable next step. Popular front-end frameworks (React, Vue, Angular, Svelte) build on exactly the ideas in this tutorial; learn the language first, and the frameworks will make sense.
Debugging: besides console.log (also console.table(array), console.error, console.time), use the browser’s Sources panel: click a line number to set a breakpoint, and the page pauses there so you can inspect every variable and step through the code. A debugger; statement does the same from code.
15. Security basics
- Cross-site scripting (XSS). If you insert user-supplied text into the page as HTML, an attacker can include a script. Use
textContent(orcreateElement) for text. The example below shows the difference. - Never use
eval()ornew Function()on text that comes from outside. - Never trust the browser. Visitors can change any JavaScript and any request. Validate and authorise everything on the server.
- Keep secrets out of front-end code: API keys with real power, passwords, private tokens.
- Be careful with packages. Check popularity and maintenance before you install, run
npm audit, and keep dependencies up to date. - Serve your site over HTTPS (see free HTTPS with Let’s Encrypt).
<!DOCTYPE html>
<html lang="en">
<body>
<div id="safe"></div><div id="unsafe"></div>
<script>
const comment = '<img src=x onerror="document.title=\'hacked\'">'; // text a malicious visitor could post
document.querySelector("#safe").textContent = comment; // shown as harmless text
document.querySelector("#unsafe").innerHTML = comment; // the browser PARSES it, and the onerror script runs!
</script>
</body>
</html>
In that example, the first line shows the characters, while the second creates a real image tag whose error handler runs the attacker’s code. If you must insert HTML from a user (a rich text editor), clean it first with a sanitising library such as DOMPurify.
16. Project: a to-do application
Time to combine everything: HTML for structure, CSS for looks, JavaScript with DOM, events, array methods, localStorage and event delegation. Save this as a single todo.html file and open it. It has add, complete, delete, filter, a counter and it remembers your tasks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>To-do</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 2rem auto; padding: 0 1rem; color: #1e293b; }
form { display: flex; gap: .5rem; }
input[type=text] { flex: 1; padding: .6rem; border: 1px solid #94a3b8; border-radius: .5rem; font: inherit; }
button { padding: .6rem 1rem; border: 0; border-radius: .5rem; background: #4f46e5; color: #fff; font: inherit; cursor: pointer; }
ul { list-style: none; padding: 0; }
li { display: flex; align-items: center; gap: .5rem; padding: .5rem 0; border-bottom: 1px solid #e2e8f0; }
li.done span { text-decoration: line-through; color: #94a3b8; }
li span { flex: 1; }
li button { background: #ef4444; padding: .25rem .6rem; }
.filters button { background: #e2e8f0; color: #1e293b; }
.filters button[aria-pressed=true] { background: #4f46e5; color: #fff; }
</style>
</head>
<body>
<h1>My tasks</h1>
<form id="add-form">
<label for="new-task" hidden>New task</label>
<input type="text" id="new-task" placeholder="What needs doing?" required maxlength="100" autocomplete="off">
<button type="submit">Add</button>
</form>
<p class="filters">
<button type="button" data-filter="all" aria-pressed="true">All</button>
<button type="button" data-filter="active" aria-pressed="false">Active</button>
<button type="button" data-filter="done" aria-pressed="false">Done</button>
</p>
<ul id="list"></ul>
<p id="summary" aria-live="polite"></p>
<script>
const STORAGE_KEY = "todo-v1";
let tasks = loadTasks(); // [{ id, title, done }]
let filter = "all";
const form = document.querySelector("#add-form");
const input = document.querySelector("#new-task");
const list = document.querySelector("#list");
const summary = document.querySelector("#summary");
function loadTasks() {
try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? []; }
catch { return []; }
}
function saveTasks() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}
function visibleTasks() {
if (filter === "active") return tasks.filter((t) => !t.done);
if (filter === "done") return tasks.filter((t) => t.done);
return tasks;
}
function render() {
list.replaceChildren(); // clear the list
for (const task of visibleTasks()) {
const li = document.createElement("li");
li.dataset.id = task.id;
li.classList.toggle("done", task.done);
const box = document.createElement("input");
box.type = "checkbox";
box.checked = task.done;
box.setAttribute("aria-label", "Done: " + task.title);
const text = document.createElement("span");
text.textContent = task.title; // textContent: safe even for hostile text
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Delete";
remove.dataset.action = "delete";
li.append(box, text, remove);
list.append(li);
}
const open = tasks.filter((t) => !t.done).length;
summary.textContent = tasks.length === 0 ? "Nothing to do. Enjoy!" : `${open} of ${tasks.length} tasks left`;
document.querySelectorAll(".filters button").forEach((b) =>
b.setAttribute("aria-pressed", String(b.dataset.filter === filter)));
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const title = input.value.trim();
if (!title) return;
tasks.push({ id: crypto.randomUUID(), title, done: false });
input.value = "";
saveTasks();
render();
});
list.addEventListener("change", (event) => { // delegation: one listener for every checkbox
const id = event.target.closest("li")?.dataset.id;
const task = tasks.find((t) => t.id === id);
if (task) { task.done = event.target.checked; saveTasks(); render(); }
});
list.addEventListener("click", (event) => {
if (event.target.dataset.action !== "delete") return;
const id = event.target.closest("li").dataset.id;
tasks = tasks.filter((t) => t.id !== id);
saveTasks();
render();
});
document.querySelector(".filters").addEventListener("click", (event) => {
if (!event.target.dataset.filter) return;
filter = event.target.dataset.filter;
render();
});
render();
</script>
</body>
</html>
Make it better: let the user edit a task by double-clicking, add due dates and sort by them, add a “clear completed” button, show a message when storage is not available, split the code into modules, and then rebuild it with a framework to see what the framework gives you.
17. Common mistakes and FAQ
- Using
==instead of===. - Forgetting that
sort()compares as text and changes the array: pass(a, b) => a - b. - Using
varor leaving variables without a declaration (they become accidental globals). Add"use strict"or use modules. - Expecting
constto make objects immutable. It only stops re-assignment. - Copying objects with
=or{...x}and being surprised that nested data is shared: usestructuredClone. - Running the script before the elements exist (“Cannot read properties of null”): use
defer. - Forgetting
await(you get a Promise instead of the value) or forgetting thatfetchdoes not throw on HTTP errors. - Using
innerHTMLwith user text. UsetextContent. - Floating-point comparisons (
0.1 + 0.2 === 0.3). - Mutating state in many places. Keep one source of truth (like the
tasksarray above) and redraw from it.
Quick answers
Is JavaScript the same as Java? No. They are unrelated languages with similar names, for marketing reasons in 1995. The official name of the language standard is ECMAScript, and a new version appears every year.
Do I need a framework? Not to learn. Learn plain JavaScript and the DOM first, build a few small projects, then pick one framework when you need to build bigger applications. Frameworks change; the language stays.
JavaScript or Python? JavaScript for anything in the browser (it is the only choice there) and full-stack web work; Python for data, automation and scripting. Many developers know both: our Python tutorial shows the same ideas in the other language.
Where can I practise? Build the project above and then your own: a calculator, a quiz, a weather page, a habit tracker. The free MDN Web Docs (developer.mozilla.org) are the best reference, and javascript.info is an excellent long tutorial. Understanding data structures and algorithms will make you a better programmer in any language: see our algorithms tutorial (the ideas apply directly to JavaScript), and use our free JSON formatter, regex tester and JWT decoder while you work.
More tutorials like this
CSS Tutorial: Complete Guide to Layout, Flexbox, Grid and Responsive Design
A complete CSS tutorial: selectors, the cascade and specificity, the box model, flexbox, grid, responsive design, animations, variables, dark mode and a full responsive…
HTML Tutorial for Beginners: A Complete Guide from First Page to Full Website
A complete HTML tutorial for beginners: document structure, text, links, images, lists and tables, forms, semantic layout, accessibility, SEO metadata and a full landing…


