06 / 07
The basics of the language, the DOM and asynchronous flow.
JavaScript is the programming language that makes web pages interactive. HTML defines the content and CSS the appearance; when a page does more than show fixed information (a menu opens, a form is validated, data arrives from a server), JavaScript is behind it.1 The same language also runs outside the browser with Node.js; the development server, the build tools and the packages in a React project are JavaScript too.
This lesson does not cover the whole language. It touches briefly on what you need before moving to React, and points to a source for going deeper on each topic.
JavaScript is added to a page with a <script> tag. The modern way is type="module"; module scripts wait until the HTML has been parsed, which makes them safe to put in the <head>.1
<script type="module" src="main.js"></script>The quickest way to try something is the browser's DevTools console: open it on any page and type console.log("hello").
There are three ways to declare a variable. var is old and has error-prone behaviour, so it is no longer used.2
const site = "ViraStack"; // cannot be reassigned
let count = 0; // can be reassigned
count = count + 1;MDN's rule is short: "Use const when you can, and use let when you have to."2 const stops the variable from being reassigned; it does not stop the object inside it from changing.
JavaScript is a dynamically typed language: you do not declare a variable's type, and the same variable can hold values of different types. The basic (primitive) types are string, number, boolean, null, undefined, bigint and symbol; everything else (arrays and functions included) is an object.3
The language converts between types on its own when it has to. That is why comparisons use ===; == converts first, and the result is hard to predict.4
0 == "0"; // true
0 === "0"; // falseTip
To catch type errors before the code runs, most JavaScript projects now use TypeScript. In State of JS 2025, 40% of respondents said they write TypeScript only.5 TypeScript gets its own section later in this roadmap.
A function is a reusable block of code. Two ways of writing one are common: the classic function declaration and the shorter arrow function.6
function add(a, b) {
return a + b;
}
const multiply = (a, b = 1) => a * b; // b is 1 when nothing is passedReact components and event handlers are mostly written as arrow functions.
A function remembers the variables where it was defined, even after that scope has finished. This is called a closure.67
function createCounter() {
let count = 0;
return () => ++count;
}
const increment = createCounter();
increment(); // 1
increment(); // 2Closures are the basis for understanding how hooks and event handlers work in React: a function inside a component "remembers" the state from the render it was created in.
An object is made of key and value pairs, an array of ordered values. Data from a server is nearly always a combination of the two.
const user = { name: "Jane", age: 28 };
const products = [
{ name: "Pen", price: 20 },
{ name: "Notebook", price: 45 },
];Destructuring pulls values out of an object or an array into variables in a single line. Spread (...) unpacks an object or an array inside another one.89
const { name, age } = user;
const updatedUser = { ...user, age: 29 }; // a new object; the original is untouched
const allProducts = [...products, { name: "Eraser", price: 10 }];Spread makes a shallow copy: nested objects are not copied, and the same reference is shared.9 In React you build a new copy this way instead of changing state in place.
These are the methods you will use most:10
| Method | What it does |
|---|---|
map | Transforms every item and returns a new array |
filter | Returns a new array of the items that match a condition |
find | Returns the first item that matches a condition |
reduce | Reduces the array to a single value (a total, for instance) |
const names = products.map((p) => p.name); // ["Pen", "Notebook"]
const cheapProducts = products.filter((p) => p.price < 30);
const total = products.reduce((sum, p) => sum + p.price, 0); // 65Warning
sort, reverse and splice change the original array.10 Copy it before using them on React state: [...items].sort().
Two short operators help with values that may be missing: user.address?.city returns undefined instead of throwing when there is no address, and value ?? "default" uses the right-hand side when the value is null or undefined.11
The browser reads your HTML and turns it into a tree called the DOM (Document Object Model). JavaScript can reach into that tree to read and change the content.12
const heading = document.querySelector("h1");
heading.textContent = "New title";
heading.classList.add("active");Events are things that happen in the system and that your code can react to: a click, a key press, a form being submitted. To react to one, use addEventListener.13
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault(); // stops the page from reloading
console.log("Form submitted");
});Tip
In React you do not change the DOM by hand like this; you update state and React updates the DOM for you. Knowing what happens underneath still makes it easier to see why React does what it does.
Work such as fetching data from a server takes time. Rather than waiting, JavaScript carries on and continues once the result arrives. That wait is represented by a Promise: an object carrying the result of an operation that will either complete or fail later.14
The readable way to work with promises is async/await. await makes the code read from top to bottom like synchronous code, and errors are caught with try/catch.15
async function fetchProducts() {
try {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const products = await response.json();
console.log(products);
} catch (error) {
console.error(error);
}
}Caution
fetch does not throw when the server returns a 404 or a 500; it only fails on a network error. That is why response.ok always has to be checked.16
JavaScript runs on a single thread and finishes one piece of work before it moves to the next.17 Waiting work (timers, settled promises, clicks) lines up in a queue, and the event loop runs them in turn. The shortest way to see this is Lydia Hallie's 12-minute video.18
As a project grows, the code is split across files. Each file is a module: it hands out what it wants to share with export and takes what it needs from another file with import.19
// price.js
export const TAX_RATE = 0.2;
export default function addTax(amount) {
return amount * (1 + TAX_RATE);
}
// main.js
import addTax, { TAX_RATE } from "./price.js";The ones in curly braces are named exports, and there can be as many as you like. The one without braces is the default export, one per module.19 In a React project every component is a module, and you will see both forms constantly.
Guide from start to finish: javascript.info; the language and browser (DOM, events) sections, kept current.20
Hands-on course: MDN's Dynamic scripting with JavaScript module.21
Free book: the 4th edition of Marijn Haverbeke's Eloquent JavaScript.22
Checklist before React: Kent C. Dodds's "JavaScript to Know for React".11
Talk: Philip Roberts on the event loop (JSConf EU 2014, 27 min).23
Talk: Jake Archibald on the browser's event loop (JSConf.Asia 2018, 35 min).24
Sources
What the language is and how to add a script to a page (`defer`, `async`, `type="module"`).
The difference between `var`, `let` and `const`; "Use `const` when you can, and use `let` when you have to."
The primitive types, and the dynamic and weak type system.
Using `===` almost always, and avoiding `==`.
The share writing TypeScript only, and missing static types as the language's biggest pain point.
Declarations, expressions, arrow functions, default parameters and closures.
Closures explained step by step, with diagrams.
Object and array destructuring, default values and rest.
Spread in arrays and objects; the shallow copy.
`map`, `filter`, `find` and `reduce`; which methods change the original and which return a new array.
: — The JS features React needs: destructuring, spread, array methods, `?.`, `??` and async/await.
The DOM tree, `querySelector`, `textContent` and `classList`.
`addEventListener`, the event object and `preventDefault`.
What a promise is, chaining and `Promise.all`.
The same `fetch` example, first as a promise chain and then with `async`/`await`.
`fetch` not rejecting on HTTP errors, and checking `response.ok`.
The job queue, the event loop and run-to-completion.
About 12 minutes. The call stack and the task and microtask queues, animated.
`export`/`import`, named and default exports, `type="module"`.
A JavaScript guide from start to finish, with language and browser sections.
A hands-on module from variables to the DOM, `fetch` and JSON.
: — A 2024 book, free to read, with language, browser and Node sections.
: — 27 minutes. A visual walk through the call stack and the callback queue.
: — 35 minutes. Tasks, microtasks, `requestAnimationFrame` and render order.
Check the lesson's main ideas with three questions.
Your progress is stored only in this browser.
Last updated: November 3, 2026