Coding · Programming languages
JavaScript tutorial for beginners
Short answer
JavaScript is the programming language of the web: every browser runs it, and Node.js runs it on servers and the command line. Declare variables with const and let, write functions as declarations or arrow functions, store data in arrays and objects, and handle slow work such as network requests with promises and async/await. Run node hello.js or open the browser console to start.
What JavaScript is and what it is used for
JavaScript is a dynamically typed language standardized as ECMAScript. It was created for web pages, where it reacts to clicks, updates the page and talks to servers. Today it also runs on servers and tools through Node.js, Deno and Bun, in desktop apps (Electron) and in mobile apps (React Native). Front-end developers, full-stack developers and anyone building for the web use it. The modern syntax in this page (let, const, arrow functions, classes, modules) comes from ES2015 and later editions.
Run Hello, world
Option 1: open any web page, press F12 (or Cmd+Option+J on a Mac) to open the developer console, and type the line below. Option 2: install Node.js from nodejs.org, save the line as hello.js and run it.
console.log("Hello, world");node hello.js
# Hello, worldVariables and basic types
Use const for values that are not reassigned and let for values that change. Avoid the old var, which ignores block scope. typeof reports the type of a value.
| Type | Example | typeof |
|---|---|---|
| number | 42, 3.14, NaN | "number" |
| bigint | 10n | "bigint" |
| string | "hi", 'hi', hi ${name} | "string" |
| boolean | true, false | "boolean" |
| undefined | undefined | "undefined" |
| null | null | "object" (a historical quirk) |
| object | {}, [], functions | "object" or "function" |
const name = "Ada";
let count = 1;
count += 1;
console.log(`${name} has ${count} items`); // Ada has 2 items
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(Number("12") + 1, "12" + 1); // 13 121Control flow: if, loops and equality
Always compare with === and !==. The loose == converts types first, so 0 == "" is true.
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B"); // B
} else {
console.log("C");
}
for (let i = 0; i < 3; i++) console.log(i); // 0 1 2
for (const fruit of ["apple", "pear"]) console.log(fruit);
let n = 10;
while (n > 1) n = Math.floor(n / 2);
console.log(n); // 1Functions
Functions are values: you can store them in variables, pass them to other functions and return them. Arrow functions are a shorter form and are common for callbacks.
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
const square = (x) => x * x;
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(greet("Lin")); // Hello, Lin!
console.log(square(5)); // 25
console.log(sum(1, 2, 3, 4)); // 10Arrays and objects
Arrays are ordered lists; objects map string keys to values. Both are passed by reference. Map and Set are built-in alternatives when keys are not strings or values must be unique.
const nums = [3, 1, 2];
nums.push(5);
const doubled = nums.map((n) => n * 2);
const evens = nums.filter((n) => n % 2 === 0);
console.log(doubled, evens); // [ 6, 2, 4, 10 ] [ 2 ]
console.log([...nums].sort((a, b) => a - b)); // [ 1, 2, 3, 5 ]
const user = { name: "Ann", age: 31 };
user.city = "Oslo";
const { name, age } = user; // destructuring
console.log(name, age, Object.keys(user)); // Ann 31 [ 'name', 'age', 'city' ]
console.log(JSON.stringify(user)); // {"name":"Ann","age":31,"city":"Oslo"}Signature feature: asynchronous code with promises
JavaScript runs your code on one thread with an event loop. Slow operations (timers, network, files) do not block; they return a promise that settles later. async functions let you write this code top to bottom with await.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
console.log("start");
await wait(500);
console.log("half a second later");
const [a, b] = await Promise.all([wait(100).then(() => 1), wait(200).then(() => 2)]);
console.log(a + b); // 3
}
main();
console.log("main() was called"); // prints before "half a second later"Classes (class Dog extends Animal {}), modules (import and export), optional chaining (user?.address?.city) and the nullish operator (value ?? "default") are other modern features you will use often.
Error handling
Throw Error objects and catch them with try/catch. With async functions, a rejected promise becomes an exception at the await.
function parseAge(text) {
const age = Number(text);
if (!Number.isInteger(age) || age < 0) {
throw new Error(`invalid age: ${text}`);
}
return age;
}
try {
console.log(parseAge("41")); // 41
console.log(parseAge("abc"));
} catch (err) {
console.log(err.message); // invalid age: abc
} finally {
console.log("done");
}A small complete program: fetch and summarize
This Node.js script (Node 18 or later has fetch built in) downloads JSON from a public API and prints a short summary. Save it as repos.mjs and run node repos.mjs nodejs.
const org = process.argv[2] ?? "nodejs";
async function topRepos(name, n = 3) {
const res = await fetch(`https://api.github.com/orgs/${name}/repos?per_page=100`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const repos = await res.json();
return repos
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, n)
.map((r) => `${r.stargazers_count}\t${r.name}`);
}
try {
const lines = await topRepos(org);
console.log(lines.join("\n"));
} catch (err) {
console.error("failed:", err.message);
process.exitCode = 1;
}The .mjs extension makes the file an ES module, which allows await at the top level.
Common beginner mistakes
- Using
==instead of===, which leads to surprising type conversions. - Forgetting
await, so you get a pendingPromiseobject instead of the value. - Expecting
constto make an object immutable. It only stops reassignment;obj.x = 1still works. UseObject.freezeif needed. - Comparing objects or arrays with
===, which checks identity, not contents. - Losing
thiswhen passing a method as a callback. Use an arrow function or.bind(obj).
Where to go next
Read the MDN JavaScript Guide, which is the most complete free reference, and practice with the browser DOM (document.querySelector, events). Then learn npm and modules, a framework such as React, Vue or Svelte for the front end, or Node.js for servers. Adding TypeScript on top of JavaScript gives you static types and better editor help.
FAQ
Is JavaScript the same as Java?
No. They are unrelated languages with similar names. Java is statically typed and compiled to JVM bytecode; JavaScript is dynamically typed and runs in browsers and Node.js.
Should I use let, const or var?
Use const by default and let when you need to reassign. Avoid var, because it is function-scoped and hoisted, which causes bugs.
What is the difference between null and undefined?
undefined means a variable or property was never given a value. null is a value you assign on purpose to mean nothing.
Why does 0.1 + 0.2 not equal 0.3?
JavaScript numbers are 64-bit binary floating point, which cannot store 0.1 exactly. Round for display, or use integers (for example cents) for money.
Do I need Node.js to learn JavaScript?
No. Every browser can run JavaScript in its developer console. Node.js is useful when you want to run scripts from files or build servers and tools.