// Vieles ist wie in anderen Sprachen …
let names = ['Alice', 'Bob', 'Carol', 'Dave'];
for (let name of names) {
if (name.length > 3)
console.log(`${name} ist ein kurzer Name.`);
else
console.log(`${name} ist ein langer Name.`);
}
// … mit kleinen Eigenheiten
let sizeOfAllNames = names.reduce((sum, name) => sum + name.length, 0);
console.log(`Alle Namen sind zusammen ${sizeOfAllNames} Zeichen lang.`);
Javaim Name
The by-design purpose of JavaScript, was to make the monkey dance when you moused over it.
Scripts were often a single line. We considered ten line scripts to be pretty normal, hundred line scripts to be huge, and thousand line scripts were unheard of. The language was absolutely not designed for programming in the large, and our implementation decisions, performance targets, and so on, were based on that assumption.
// Kommentar
/* Kommentar */
if (1 >= 2) {
console.log("Nope");
}
else if (1 == 1) {
console.log("Yep");
}
else {
console.log("Nope");
}
// logische Operatoren
if (username && password) do_stuff();
let name = user && user.getName();
let name = user.name || "default";
// Unäre Operatoren
!!user.name // true / false
+"300" // 300
i++
// Ternäre Operatoren
bedingung ? anweisung() : anweisung2();
numerus = people.length == 1 ? "Person" : "Personen";
while (bedingung) { anweisungen; }
do { anweisungen; } while (bedingung);
for (let i = 0; i < 100; i++) { anweisungen; }
var eins = 1; // ⚠️ function scope
zwei = 2; // ⚠️ automatisch global
let drei = 3; // block scope, veränderbar
drei = 4;
const vier = 4; // block scope, unveränderbar
vier = 5; // 🛑 Zonk
Number
String
Boolean
Function
Object
Object
Function
Array
Date
RegExp
null
undefined
3 // 3
3.14 // 3.14
9 / 2 // 4.5
2 * (3 + 4) // 14
0.5 + 0.5 // 1
0.1 + 0.2 // 0.30000000000000004
0.1 + 0.2 === 0.3 // false
Infinity
, -Infinity
, NaN
, Number.MAX_SAFE_INTEGER
, Number.MAX_VALUE
let vorname = "Alice";
let nachname = 'Bob';
let full = vorname + ' ' + nachname;
let satz = `Der ganze Name ist ${vorname} ${nachname}`;
1 + 2 + "3" // "123"
1 - 2 - "3" // -4
1 * 2 * "3" // 6
1 == "1" // true
1 === "1" // false
"a" < "b" // true
function hallo (name = 'unbekannt') {
alert(`Hallo ${name}!`);
}
let plus = function (a, b) { return a + b; }
plus(1, 2); // 3
let plus = (a, b) => a + b; // arrow function
'abcdefg'.charAt(2).toUpperCase(); // 'C'
'abcdefg'['charAt'](2)['toUpperCase'](); // 'C'
let namen = ['Alice', 'Bob'];
let person = {
name: 'Alice',
alter: 42
}
let brot = { // Object
name: "Matze", // Property
zutaten: [ // Array
{ "name": "Mehl", "menge": 2 },
{ name: "Wasser", menge: 1 }
],
getRezept: function () { // Method
return this.zutaten[0].name +
" + " + this["zutaten"][1]["name"] +
" = " + this.name;
}
};
// member operator
brot.name === brot["name"];
function Person(name, alter) {
this.name = name;
this.alter = alter;
}
function introduce(person) {
return "Hallo, ich heiße " + person.name +
" und bin " + person.alter + " Jahre alt.";
}
let alice = new Person('alice', 42);
alice.alter == 42;
introduce(alice);
function Person(name, alter) {
this.name = name;
this.alter = alter;
this.introduce = function() {
return "Hallo, ich heiße " + this.name + " und bin " + this.alter + " Jahre alt.";
}
}
let alice = new Person('Alice', 42);
alice.introduce();
function Person(name, alter) {
this.name = name;
this.alter = alter;
}
Person.prototype.introduce = function() {
return "Hallo, ich heiße " + this.name + " und bin " + this.alter + " Jahre alt.";
}
let alice = new Person('Alice', 42);
alice.introduce();
Klassen
class Person {
constructor(name, alter) {
this.name = name;
this.alter = alter;
}
introduce() {
return `Hallo, ich heiße ${this.name} und bin ${this.alter} Jahre alt.`;
}
}
let alice = new Person('Alice', 42);
alice.introduce();
Thread.sleep
wie in JavasetTimeout(funktion, verzögerung, params)
→ IDsetInterval(funktion, verzögerung, params)
→ IDfunction sayTime() { console.log(`Es ist ${new Date().toLocaleTimeString()}`); }
sayTime();
// setzen
const idT = setTimeout(sayTime, 1000); // einmal nach ~1s
const idI = setInterval(sayTime, 5000); // alle ~5s
// löschen
clearTimeout(idT);
clearInterval(idI);
[1, 2, 3].includes(2); // true
[1, 2, 3].find(value => value === 2); // 2
[1, 2, 3].some(value => value === 2); // true
[1, 2, 3].every(value => value === 2); // false
[1, 2, 3].filter(value => value !== 2); // [1, 3]
[1, 2, 3].map(value => value * 2); // [2, 4, 6]
[1, 2, 3].reduce((sum, value) => sum + value, 0); // 6
const anschrift = {
strasse: 'Schwarzstraße 13-15',
plz: '5020',
}
const strasse = anschrift.strasse; // alt
const { plz } = anschrift; // neu
const adresse = ['Schwarzstraße 13-15', '5020', 'Salzburg', 'Österreich'];
const [strasse, plz, stadt] = adresse; // auch mit arrays
console.log(`Post bitte an ${strasse} in ${plz} ${stadt}`);
const add = (a, b) => {
a = a === undefined ? 0 : a; // meh
b = b === undefined ? 0 : b;
return a + b;
};
const add = (a = 0, b = 0) => a + b; // yeah
add() === 0
add(1) === 1
add(undefined, 2) === 2
function greetUser ({ name = 'unbekannt' }) {} // auch für Objekte
undefined
, nicht für null
let vorname = 'Alice';
let alterInJahren = 42;
const lang = { vorname: vorname, alterInJahren: alterInJahren }; // 😕
const kurz = { vorname, alterInJahren }; // 🙂
...
const adresse = ['Schwarzstraße 13-15', '5020', 'Salzburg', 'Österreich'];
const [strasse, ...rest] = adresse;
console.log(rest); // ['5020', 'Salzburg', 'Österreich']
const charMap = { a: 1, b: 2, c: 3, d: 4 };
const { b, d , ...rest} = charMap;
console.log(rest); // { a: 1, c: 3 }
...
Math.max(3, 2, 5, 4) // 5
const values = [1, 5, 3, 9, 4];
Math.max(...values) // 9
const newArray = [1, 2, 3, ...values] // [1, 2, 3, 1, 5, 3, 9, 4]
const defaultValues = { name: 'unbekannt', anschrift: 'unbekannt' };
const person = { name: 'Alice' }
const merged = { ...defaultValues, ...person };
console.log(merged); // { name: 'Alice', anschrift: 'unbekannt' }
??
function showAmount (value) {
const amount = value || 'unbekannt';
console.log(amount);
}
showAmount(null) // 'unbekannt'
showAmount(1000) // 1000
showAmount(0) // 'unbekannt' 😱
function showAmount (value) {
const amount = value ?? 'unbekannt'; // nur bei `null` und `undefined`
console.log(amount);
}
showAmount(0) // 0 🙂
?.
function (user) { // user === null
console.log(user.account.iban)
// -> TypeError: Cannot read property 'account' of undefined
if (user && user.account && user.account.iban) {
console.log(user.account.iban) // 😕
}
console.log(user?.account?.iban) // 🙂
user?.accounts?.[0].iban?.format?.() // 😶
}
async function getUser (id) {
if (!userCache[id]) {
const response = await fetch(`${apiURL}/users/${id}`)
const json = await response.json();
userCache[id] = json.data;
}
return userCache[id];
}
const sleep = delay => new Promise(resolve => setTimeout(resolve, delay));
console.log('1');
await sleep(1000); // sleep 1 second
console.log('2');