JavaScript Basics

The language that makes a website interactive, also used on this website.

Last updated: September 23, 2026

Adding JavaScript

JavaScript runs in the browser and can change a page after it has loaded.

<script src="script.js"></script>Links an external JavaScript file, the usual approach
<script>...</script>JavaScript directly in the HTML file, without an external file
console.log(...)Prints a value in the browser's developer console, for testing

Variables

Stores a value under a name.

let number = 5;A variable whose value can change later
const name = "Elias";A variable whose value stays fixed afterward
var old = 1;Older syntax, mostly replaced by let and const today

Functions

Groups reusable code under a name.

function add(a, b) { return a + b; }Classic function syntax
const add = (a, b) => a + b;Shorter syntax, called an arrow function
add(2, 3)Calls the function, the result is 5

Working with the document (DOM)

The DOM is the structure of the HTML page, as JavaScript sees and can change it.

document.querySelector(".card")Finds the first element with this class
element.textContent = "Text"Changes an element's visible text
element.classList.add("active")Adds a CSS class to an element, for example for styling

Reacting to events

Events trigger code, for example when someone clicks.

element.addEventListener("click", () => { ... })Runs code as soon as the element is clicked
"input"Fires whenever the content of an input field changes
"submit"Fires when a form is submitted

Conditions and loops

Just like in other programming languages, only with its own syntax.

if (number > 0) { ... }Runs code only if the condition is met
for (let i = 0; i < 10; i++) { ... }Repeats a block of code exactly ten times
array.forEach(item => { ... })Runs code for every item in a list

Common data types

JavaScript figures out the type automatically, you don't have to state it yourself.

NumberNumbers, whether or not they have decimal places
StringText, in single or double quotes
BooleanOnly true or false
ArrayA list of several values, for example [1, 2, 3]
ObjectStores several named values together, for example { name: "Max", city: "Berlin" }