Home › Programming › JavaScript

JavaScript

JavaScript runs in every browser and makes pages interactive. Learn the language, then the DOM, then asynchronous code.

JavaScript is the one programming language every browser runs. It started small and grew into a full, modern language — and with Node.js it runs on servers too (see the Node.js tutorial).

Variables and types

const name = "Ada";     // cannot be reassigned
let count = 0;          // can change
count = count + 1;

// types: string, number, boolean, null, undefined, object, symbol, bigint

Prefer const by default and switch to let only when you actually reassign. Avoid the old var.

Functions

function add(a, b) {
  return a + b;
}

// arrow function — shorter, and handy for callbacks
const double = (n) => n * 2;

Objects and arrays

const user = { id: 1, name: "Ada" };
user.name;            // "Ada"

const nums = [3, 1, 2];
nums.map(n => n * 2); // [6, 2, 4]
nums.filter(n => n > 1);
nums.sort((a, b) => a - b);

Touching the page (the DOM)

The DOM is the browser’s object model of the page. JavaScript reads and changes it:

const btn = document.querySelector("#save");
btn.addEventListener("click", () => {
  document.querySelector("#status").textContent = "Saved!";
});

Asynchronous code

Network calls do not finish instantly, so JavaScript does not wait — it uses promises. async/await makes them read top-to-bottom:

async function loadUser(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error("request failed");
  const data = await res.json();
  return data;
}
Mental model: JavaScript is single-threaded. Instead of blocking, it hands slow work (timers, network, clicks) to the browser and runs your callback later. That is the “event loop.”

Keep reading