JavaScript

JavaScript Resources

Cheatsheet

JavaScript Testing

JavaScript Snippets

Math.floor / ~~ Operator

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

Cast to String

Problem:

('1234' === 1234) // false 
String(string); // 'hello'
String(number); // '123'
String(boolean); // 'true'
String(array); // '1,2,3'
String(object); // '[object Object]'
String(symbolValue); // 'Symbol(123)'
String(undefinedValue); // 'undefined'
String(nullValue); // 'null'

or

var s = 123456 + '';

https://medium.com/dailyjs/5-ways-to-convert-a-value-to-string-in-javascript-6b334b2fc778

Check for Boolean

console.log(typeof true === "boolean") // true
  • Using the Boolean() wrapper function.
  • Putting two exclamation points !! (the logical NOT ! operator, twice) in front of any expression, which calls the Boolean() wrapper function.
// falsy values: false, 0, -0, 0n, null, undefined, NaN, and the empty string ""
console.log(Boolean(false)) // false

// truthy values: true, 1, -1, 1n, -1n, Infinity, -Infinity, " ", {}, []
console.log(Boolean(true)) // true

https://medium.com/javascript-in-plain-english/how-to-check-for-a-boolean-in-javascript-98fdc8aec2a7

Using Class and prototype

https://raindrop.io/collection/2707120?q=tag:prototype&sort=-sort

Using fetch to download files

fetch('example.txt')
.then(response => response.text()) 
.then(textString => {
    console.log(textString);
});
fetch('example.csv')
.then(response => response.text()) 
.then(csvString => {
    const rows = csvString.split('\n');
    for (row of rows) {
        console.log(row.split(","));
    }
});

Create a Random ID

toString(36) is an alphanumeric representation of a number (https://stackoverflow.com/a/37159754/814031)

Math.random().toString(36).substring(7)

Native Date and Time formats

const date = new Date();

const dateOptions = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};

console.log(date.toLocaleDateString("de-DE", dateOptions));

Immediately Invoked Function Expressions

(function () {
    // logic here
})();

Prototyp

Classes