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 fileconsole.log(...)Prints a value in the browser's developer console, for testingVariables
Stores a value under a name.
let number = 5;A variable whose value can change laterconst name = "Elias";A variable whose value stays fixed afterwardvar old = 1;Older syntax, mostly replaced by let and const todayFunctions
Groups reusable code under a name.
function add(a, b) { return a + b; }Classic function syntaxconst add = (a, b) => a + b;Shorter syntax, called an arrow functionadd(2, 3)Calls the function, the result is 5Working 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 classelement.textContent = "Text"Changes an element's visible textelement.classList.add("active")Adds a CSS class to an element, for example for stylingReacting 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 submittedConditions and loops
Just like in other programming languages, only with its own syntax.
if (number > 0) { ... }Runs code only if the condition is metfor (let i = 0; i < 10; i++) { ... }Repeats a block of code exactly ten timesarray.forEach(item => { ... })Runs code for every item in a listCommon data types
JavaScript figures out the type automatically, you don't have to state it yourself.
NumberNumbers, whether or not they have decimal placesStringText, in single or double quotesBooleanOnly true or falseArrayA list of several values, for example [1, 2, 3]ObjectStores several named values together, for example { name: "Max", city: "Berlin" }