// if under 18 voteable will be "Too young"
// if over 18 votable will be "Old enough"
voteable = (age < 18) ? "Too young":"Old enough";
// alternative you can write it like this
voteable = age < 18 ? "Too young":"Old enough";- https://www.youtube.com/watch?v=I5AGSH8ROSU
- https://dev.to/livecodestream/how-to-use-the-spread-operator-in-javascript-35bn
- https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
let ar = [1,2]
function test(a, b) {
console.log('a:' + a);
console.log('b:' + b);
}
test(...ar);let obj1 = {a: true};
let obj2 = {b: true};
function test({a = false, b = false}){
console.log(a);
console.log(b);
};
test({...obj1, ...obj2});const objectReturningFunction = () => {
return {a:true, b:false}
}
let a, b
;({a, b} = objectReturningFunction())
console.log(b)
// Example #2
let { hasChanged } = await getModel(modelName)
;({ hasChanged } = await getModel(modelName2))// Remove placements property from obj
const { placements, ...newObj } = obj
{
apple: true,
...(cfg.path && typeof cfg.path === 'object' ? cfg.path : {})
}- Syntax:
leftExpression ?? rightExpression- Example:
/* ---- EXAMPLE #1 ---- */
// result will be 1 and is not what we want..
let count = 0;
let result = count || 1;
console.log(result); // 1
// The nullish coalescing operator helps you to avoid this pitfall. It only returns the second operand when the first one evaluates to either null or undefined.
let count = 0;
let result = count ?? 1;
console.log(result); // 0
/* ---- EXAMPLE #2 ---- */
const result = null || undefined ?? 'OK'; // SyntaxError
const result = (null || undefined) ?? 'OK';
console.log(result); // 'OK'- If the first value is true, the second value is assigned.
let x = 10;
x &&= 5;- If the first value is false, the second value is assigned.
let x = 10;
x ||= 5;- If the first value is undefined or null, the second value is assigned.
let x;
x ??= 5;-
It is important to know that javascript will execute all stuff that is listed with those logical OR operators when something has a higher priority. This means that when you pass a Ternary Operator then it will get executed even when the first case is true because it has higher priority. You can use brackets to prevent this.
-
Example:
const res = name || lastname
// Use brackets to prevent execution of the Ternary Operator part
const res = name || (lastname || (name.startsWith('Lisa') ? await checkName() : 0))const a = 1;
const b = 2;
const example = a > b
console.log(example); // false- The in operator returns true if the specified property is in the specified object or its prototype chain.
/* ---- EXAMPLE #1 ----*/
const car = { make: 'Honda', model: 'Accord', year: 1998 };
if('make' in car) console.log(true);
else console.log(false);
/* ---- EXAMPLE #2 ----*/
const car = { make: 'Honda', model: 'Accord', year: 1998 };
console.log('make' in car);
// expected output: true
delete car.make;
if ('make' in car === false) {
car.make = 'Suzuki';
}
console.log(car.make);
// expected output: "Suzuki"- The typeof operator returns a string indicating the type of the unevaluated operand.
var test = 'aaa'
if(typeof test === 'string') console.log(true)Der JavaScript-Operator |> ist der Pipeline-Operator, der in der Entwicklung ist (Stand: ES2024). Er macht Code sauberer, indem er Ausdrücke schrittweise verarbeitet, ähnlich wie in einer Pipeline.
Er nimmt das Ergebnis eines Ausdrucks und gibt es als Argument an die nächste Funktion weiter.
Ohne Pipeline-Operator:
const result = double(square(increment(2)));
console.log(result); // 18Mit Pipeline-Operator:
const result = 2 |> increment |> square |> double;
console.log(result); // 182wird anincrementübergeben.- Das Ergebnis wird an
squareübergeben. - Das Ergebnis wird an
doubleübergeben.
- Bessere Lesbarkeit: Es liest sich von links nach rechts, wie man denkt.
- Weniger Klammern: Kein Verschachteln von Funktionsaufrufen nötig.
Noch experimentell, aber ein potenzieller Game-Changer! 😊
- https://www.w3schools.com/js/js_comparisons.asp
- Comparison operators are used for controlling the flow of your program. They allow you to compare two values and determine whether certain conditions are met.
- Compares two values for equality, but without considering the types.
5 == '5'; // true- This is the preferred way of comparing values because it checks both the value and the type.
5 === '5'; // false
5 === 5; // truex != 8 // truex !== 5 /falsex > 8 // falsex < 8 // falsex >= 8 // falsex <= 8 // false
- https://www.w3schools.com/js/js_arithmetic.asp
- Arithmetic operators perform arithmetic on numbers (literals or variables).
- The exponentiation operator (**) raises the first operand to the power of the second operand.
- x ** 2 bedeutet: 5 hoch 2. -Das entspricht 5×5, was 25 ergibt.
let x = 5;
let z = x ** 2; // 25- The modulus operator (%) returns the division remainder.
let x = 5;
let y = 2;
let z = x % y;
console.log(z) // 1- The increment operator (++) increments numbers.
let x = 5;
x++; //
console.log(x) // 6- The decrement operator (--) decrements numbers.
let x = 5;
x--; //
console.log(x) // 4
Der &-Operator vergleicht die Bits beider Operanden und gibt 1 zurück, wenn beide Bits 1 sind. Andernfalls wird 0 zurückgegeben.
let a = 5; // 0101
let b = 3; // 0011
let result = a & b; // 0001 (1)
console.log(result); // Ausgabe: 1Der |-Operator vergleicht die Bits beider Operanden und gibt 1 zurück, wenn eines der beiden Bits 1 ist.
let a = 5; // 0101
let b = 3; // 0011
let result = a | b; // 0111 (7)
console.log(result); // Ausgabe: 7Der ^-Operator vergleicht die Bits beider Operanden und gibt 1 zurück, wenn die Bits unterschiedlich sind, andernfalls 0.
let a = 5; // 0101
let b = 3; // 0011
let result = a ^ b; // 0110 (6)
console.log(result); // Ausgabe: 6Der ~-Operator kehrt alle Bits des Operanden um (invertiert die Bits). Er entspricht der negativen Zahl des Operanden minus eins.
let a = 5; // 0101
let result = ~a; // 1010 (negiert 5)
console.log(result); // Ausgabe: -6Der <<-Operator verschiebt die Bits eines Operanden um eine bestimmte Anzahl nach links. Dabei werden rechts Nullen eingefügt.
let a = 5; // 0101
let result = a << 1; // 1010 (10)
console.log(result); // Ausgabe: 10Der >>-Operator verschiebt die Bits eines Operanden um eine bestimmte Anzahl nach rechts. Das Vorzeichenbit wird beibehalten, was bedeutet, dass für negative Zahlen 1 eingefügt wird.
let a = 5; // 0101
let result = a >> 1; // 0010 (2)
console.log(result); // Ausgabe: 2Der >>>-Operator verschiebt die Bits eines Operanden um eine bestimmte Anzahl nach rechts und fügt immer 0 an der linken Seite ein, unabhängig vom Vorzeichen des Operanden.
let a = -5; // 11111111111111111111111111111011
let result = a >>> 1; // 01111111111111111111111111111101 (2147483643)
console.log(result); // Ausgabe: 2147483643
- Alternative to try catch
async function fetchUserData(userId) {
const [fetchError, response] = ?= await fetch(`/api/users/${userId}`);
if (fetchError) return { error: 'Failed to fetch user data' };
const [parseError, userData] = ?= await response.json();
if (parseError) return { error: 'Failed to parse user data' };
return { userData };
}
// Usage
async function displayUserProfile(userId) {
const { error, userData } = await fetchUserData(userId);
if (error) {
console.error(error);
displayErrorMessage(error);
} else {
renderUserProfile(userData);
}
}