JSJavaScript
BeginnerLesson 2 of 16

Variables & Data Types – JavaScript

let, const, the primitive types and conversions.

With const you declare a variable that cannot be reassigned, with let one that can change. You should no longer use the old var in new code. The type belongs to the value, not to the variable.

const name = "Ada";          // string
let alter = 36;               // number
let groesse = 1.68;           // number (there is only one number type)
let aktiv = true;             // boolean
let nichts = null;            // intentionally "no value"
let unbekannt;                // undefined (nothing assigned yet)
const riesig = 12345678901234567890n;   // bigint

alter = alter + 1;
console.log(typeof name, typeof alter, typeof aktiv);
console.log(typeof nichts, typeof unbekannt, typeof riesig);
Warningtypeof null returns "object" – a historical mistake in the language that was never fixed. Always check for null with === null.

With template literals (backticks) you build text with embedded expressions. They may span multiple lines:

const stadt = "London";
console.log(`${name} is ${alter} and lives in ${stadt}`);
console.log(`2 + 3 = ${2 + 3}`);

You handle conversions with Number(), String() and Boolean(). Careful: the + operator concatenates as soon as a string is involved – all other arithmetic operators convert to numbers.

console.log(Number("42") + 1);      // 43
console.log("5" + 3, "5" - 3);       // 53 2
console.log(7 / 2, Math.floor(7 / 2), 7 % 2, 2 ** 10);   // 3.5 3 1 1024
console.log(Number("abc"));           // NaN (Not a Number)
console.log(0.1 + 0.2);               // 0.30000000000000004
console.log((0.1 + 0.2).toFixed(2));  // "0.30"
WarningFloating-point numbers are stored in binary: 0.1 + 0.2 !== 0.3. For money, calculate in cents (integers) or round deliberately with toFixed.