Basic introduction to JavaScript
JavaScript is the programming language of the web browser. It makes pages interactive: menus that open, forms that check what you typed, maps and charts that load data. With Node.js it also runs on servers and on the Unix command line.
Despite the name, JavaScript has nothing to do with Java. The name was a marketing decision in 1995; the official standard is called ECMAScript.
Running JavaScript
- In the browser: press F12 and open the Console tab. Type
2 + 2and press Enter. - In a page: put code in a file and load it with
<script src="app.js" defer></script>before</head>. - On Unix: install Node.js (
sudo apt install nodejs, or a current version from nodejs.org) and runnode app.js.
The basics
const name = "Ann"; // a value that will not be reassigned
let count = 3; // a value that can change
count = count + 1;
const users = ["ann", "bob", "eve"]; // array
const server = { host: "web1", port: 443 }; // object
console.log(`Hello ${name}, you have ${count} messages`); // template string
console.log(users.length, server.host);
for (const u of users) {
console.log("user:", u);
}
function greet(who, greeting = "Hello") {
return `${greeting}, ${who}!`;
}
const shout = (text) => text.toUpperCase(); // arrow function
if (count === 0) {
console.log("no messages");
} else if (count < 10) {
console.log("a few");
}
Use const by default and let when a value changes; avoid the old var. Compare with ===, which does not convert types ("1" == 1 is true, "1" === 1 is false).
Working with arrays
const sizes = [120, 4096, 38, 2048];
const big = sizes.filter(n => n > 1000); // [4096, 2048]
const kb = sizes.map(n => n / 1024); // convert each value
const total = sizes.reduce((a, b) => a + b, 0); // 6302
sizes.sort((a, b) => a - b); // numeric sort
Changing the page
The browser exposes the page as the DOM (Document Object Model). JavaScript can find elements, change them and react to clicks:
<button id="toggle">Show details</button>
<p id="details" hidden>Here are the details.</p>
<script>
const button = document.querySelector("#toggle");
const details = document.querySelector("#details");
button.addEventListener("click", () => {
details.hidden = !details.hidden;
button.textContent = details.hidden ? "Show details" : "Hide details";
});
</script>
Use textContent to insert text. Assigning user input to innerHTML lets attackers inject their own scripts.
Loading data with fetch
async function loadStatus() {
const response = await fetch("/api/status.json");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
document.querySelector("#status").textContent = data.message;
}
loadStatus().catch(err => console.error(err));
async and await let you write code that waits for the network without freezing the page.
JavaScript on the server and command line
// files.mjs - list the largest files in a directory (run: node files.mjs /var/log)
import { readdir, stat } from "node:fs/promises";
import { join } from "node:path";
const dir = process.argv[2] ?? ".";
const entries = await readdir(dir);
const sizes = [];
for (const name of entries) {
const s = await stat(join(dir, name));
if (s.isFile()) sizes.push([s.size, name]);
}
sizes.sort((a, b) => b[0] - a[0]).slice(0, 5)
.forEach(([size, name]) => console.log(size, name));
Node.js from nodejs.org comes with npm to install libraries; with the Debian or Ubuntu package, install it separately with sudo apt install npm. Only use well-maintained packages, and run npm audit to check for known vulnerabilities.
Learn more
- MDN JavaScript Guide: the standard free reference and tutorial.
- The Modern JavaScript Tutorial (javascript.info): thorough, from basics to advanced.
- Eloquent JavaScript: a free book that also teaches programming.
- Node.js: Learn: official introduction to Node.js.