JSJavaScript
BeginnerLesson 6 of 16

Arrays, Objects, Map & Set – JavaScript

The most important data structures – and what const really means.

Arrays are ordered, mutable lists of arbitrary values. The index starts at 0. With at(-1) you access from the end.

const zahlen = [3, 1, 2];
zahlen.push(5);
zahlen.sort();
console.log(zahlen, zahlen[0], zahlen.at(-1), zahlen.slice(1, 3), zahlen.length);
console.log(zahlen.includes(2), zahlen.indexOf(5));

Objects are collections of key-value pairs – the foundation of almost all data in JavaScript (and the basis of JSON).

const person = { name: "Ada", alter: 36 };
person.stadt = "London";
console.log(person.name, person["alter"]);
console.log("email" in person, person.email);   // false undefined
delete person.alter;
console.log(Object.keys(person), Object.values(person));

Set stores only unique values, Map is a mapping with arbitrary key types and guaranteed order:

const einzigartig = new Set([1, 2, 2, 3, 3]);
console.log(einzigartig.size, [...einzigartig]);   // 3 [1, 2, 3]

const m = new Map([["a", 1]]);
m.set("b", 2);
console.log(m.get("b"), m.size, m.has("z"));
Warningconst only prevents reassigning the variable – the contents of an array or object remain mutable. Also, with arrays/objects b = a copies only the reference.
const a = [1, 2];
const b = a;
b.push(3);
console.log(a);            // [1, 2, 3] – the same array!
const c = [...a];          // shallow copy
c.push(4);
console.log(a.length, c.length);   // 3 4