JavaScript Spickzettel

JavaScript Spickzettel

Wenn Sie alle paar Jahre JavaScript schreiben, vergessen Sie leicht die Syntax. In diesem Fall können Sie diesen Spickzettel nutzen.

Hilfreiche Referenzen

Kommentare

// Comment line
/* Block comment */

Script Platzierung

Die Platzierung von Skripten am Ende des <body>-Elements verbessert die Anzeigegeschwindigkeit, da die Interpretation der Skripte die Anzeige verlangsamt.

<body>
<script>
console.log("Hello world");
</script>
</body>
<html>
<head> <meta charset="UTF-8"> </head>
<body>
<p>Hello <input id="message"></p>

<script>
 setInterval(function(){
  var messageInput = document.getElementById("message");
  console.log(messageInput);
  window.alert(messageInput.value);
 }, 10000);

</script>
</body>
</html>

document.write fügt Text in die Webseite ein.

Console Log

Chrome Entwicklertools – Strg + Umschalt + I

console.log(42); //gibt 42 in der Console (Developer Tools) aus
//string:
console.log("Hello world");
console.log('Hello world');
console.log('I love "coding"');
console.log("I love 'coding'");

Arithmetische Operatoren

console.log(3+4); // =7
console.log(5-1); // =4
console.log(4*2); // =8
console.log(9/3); // =3
//Modulo:
console.log(11%3); // =2
console.log(12%3); // =0

String concatenation

console.log("I love to" + "code");

Properties

console.log("Hello".length); // prints 5

Methoden

console.log("Hello".toUpperCase()); // prints HELLO
console.log("Hey".startsWith("He")); // prints true
console.log("Hey".startsWith("Hello")); // prints false

.trim //remove whitespace
.trimStart() 
.trimEnd()

console.log(Math.random()); // prints random Number
Math.floor() // rounds down to the nearest whole number
Math.ceil() // rounds up to the nearest whole number

Nesting

console.log(
  Math.floor(
    Math.random() * 100
    )
  );

Integer

console.log(Number.isInteger(2024)); // prints true
console.log(Number.isInteger(2024.5)); // prints false

Variablen

  • var – universal
  • let – kann mit einem anderen Wert neu zugewiesen werden
  • const – Konstante

Wenn wir einer mit dem Schlüsselwort „let“ deklarierten Variablen keinen Wert zuweisen, hat sie automatisch den Wert „undefiniert“.

„const“ ohne Wert – führt zu SyntaxError

„const“ neuen Wert zuweisen – führt zu TypeError

Mathematische Zuweisungsoperatoren

let w = 4;
w = w + 1; // 5

let w2 = 4;
w2 + = 1 // 5, "+ = 1" bedeutet "erhöhen um 1", "+ = x" erhöhen um x

let w3 = 4;
w3 ++; // 5, "++" bedeutet "um eins erhöhen"

- = x; // verringern um x
* = x; // multiplizieren mit x
/ = x; // teilen durch x
++ // um eins erhöhen
-- // um eins verringern

let a =1;
a++; // Can be written as a = a + 1
console.log(a); // Output: 2

let b =2;
b += 2; // Can be written as a = a + 2
console.log(b); // Output: 4

let x = 20;
x -= 5; // Can be written as x = x - 5
console.log(x); // Output: 15

let y = 50;
y *= 2; // Can be written as y = y * 2
console.log(y); // Output: 100

let z = 8;
z /= 2; // Can be written as z = z / 2
console.log(z); // Output: 4

String concatenation with variables

let myCat = 'Kleopatra';
console.log('Meine Katze heißt ' + myCat + ' !')

oder mit Escape Backticks – template literals. String interpolation.

let myCat = 'Kleopatra';
console.log(`Meine Katze heißt ${myCat} !`)

typeof Operator

Returns datatype as string

let myName = "Denis";
console.log(typeof myName);

Conditional statements

if, else if, else

Innerhalb von Klammern () wird eine Bedingung angegeben, die als wahr oder falsch ausgewertet wird.

Wenn die Bedingung wahr ist, wird der Code innerhalb der geschweiften Klammern {} ausgeführt.

Wenn die Bedingung falsch ist, wird der Block nicht ausgeführt.

if (true) { //<-condition
 console.log("This message will print!"); // <- execution
}
let sale = true;
if (sale) {console.log("Buy now!")};

If … Else

if (false) {
	console.log("The code in this block wont run!");
	} else {
		console.log("But the code in this block will!")
		};

Vergleichsoperatoren

  • < less than // 10 < 12 evaluates to true
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to
  • === is equal to (strict equality, both type and value)
  • !== is not equal to

Logische Operatoren

  • && and
  • || or
  • ! not

„Truthy“ & „falsy“ assignment

let username = "";
let defaultName = username || "Fremder"; // || or. If username "falsy", print "Fremder"
console.log(defaultName); // prints "Fremder"

Ternary Operator

Kürzere if .. else Statements

Statt diesem Code:

let isNightTime = true;
if (isNightTime) {
	console.log("Turn on the lights!");
	} else {
		console.log("Turn on the lights!");
		};

Kann ich auch so schreiben:

let isNightTime = true;

isNightTime ? 
console.log("Turn on the lights!") //if true   
: 
console.log("Turn on the lights!"); // if false                                        

Oder

let favoritePhrase = "Love that!";

favoritePhrase ===  "Love that!" ? //condition 
console.log("I love that!") //if true   
: 
console.log("I don't love that!"); // if false    

Else if

if ...
  else if ...
else ...

Switch

Wie CASE

let groceryItem = "papaya";

switch (groceryItem) {
	case "tomato":
		console.log("Tomatoes are 0.49 CHF");
		break;
	case "lime":
		console.log("Limes are 1.49 CHF");
		break;	
	case "papaya":
		console.log("Papayas are 1.29 CHF");
		break;	
	default:
		console.log("Invalid item");
		break;	
}       

Random number

Von 0 bis 999

let randomNumber = Math.floor(Math.random() * 1000);

console.log(randomNumber);

Funktionen

Funktionen ermöglichen es, eine bestimmte Aufgabe mehrfach auszuführen. Funktionen stellen einen wiederverwendbaren Codeblock dar, der eine Folge von Anweisungen zusammenfasst, um eine bestimmte Aufgabe zu erfüllen.

function greetWorld() {
  console.log('Hello World!');
}

greetWorld(); // Output: Hello World!

Mit Parameter:

function greetWorld(name) {
  console.log('Hello ' + name);
}

let name = "Denis"
greetWorld(name); // Output: Hello Denis

Zwei Zahlen multiplizieren

// Funktion zur Multiplikation von zwei Zahlen
function multiplyNumbers(num1, num2) {
    // Multipliziere die Zahlen
    return num1 * num2;
}

// Vom Benutzer bereitgestellte Eingaben
let number1 = 2;
let number2 = 3;

// Rufe die Funktion mit den Eingaben auf und speichere das Ergebnis in einer Variablen
let number3 = multiplyNumbers(number1, number2);

// Gib das Ergebnis aus
console.log(`The result of multiplying ${number1} and ${number2} is ${number3}`);

Und als Klasse:

// Definition der Klasse
class Multiplier {
    // Konstruktor (optional, falls Initialisierung benötigt wird)
    constructor() {}

    // Methode zur Multiplikation von zwei Zahlen
    multiplyNumbers(num1, num2) {
        return num1 * num2;
    }
}

// Instanziierung der Klasse
const multiplier = new Multiplier();

// Vom Benutzer bereitgestellte Eingaben
let number1 = 2;
let number2 = 3;

// Aufruf der Methode und Speichern des Ergebnisses
let number3 = multiplier.multiplyNumbers(number1, number2);

// Ausgabe des Ergebnisses
console.log(`The result of multiplying ${number1} and ${number2} is ${number3}`);

JSON

JavaScrip Object Notation. Dateiendung .json. Speichert Informationen in einer Reihe von Schlüssel-Wert-Paaren. Ähnlich wie Dictionaries in Python.

JSON Syntax In One Video

JavaScript JSON

{
	"name": "Denis",
	"age": 23,
	"note": 1.8,
	"male": true,
	"flaws": null
}

Kann auch innerhalb eines Objekts gespeichert werden.

{
	"person": {
	"name": "Denis",
	"age": 23,
	"note": 1.8,
	"male": true,
	"flaws": null
	}
}
// access via person.name

Auch Listen möglich

{
	"person": {
	"name": "Denis",
	"age": 23,
	"note": 1.8,
	"male": true,
	"flaws": null,
	"hobbies": ["snowboard", "books", "writing"]
	}
}

Listen von Objekten

{
	"person": {
	"name": "Denis",
	"age": 23,
	"note": 1.8,
	"male": true,
	"flaws": null,
	"hobbies": ["snowboard", "books", "writing"],
	"friends": [
		{
		 "name": "Stephan",
		 "age": 33
		},
				{
		 "name": "Adam",
		 "age": 34
		},
		]
	}
}
0 Kommentare

Hinterlasse einen Kommentar

An der Diskussion beteiligen?
Hinterlasse uns deinen Kommentar!

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.