JavaScript
JavaScript Resources
- The Vanilla JS Toolkit - great basic JavaScript solutions
- https://umaar.com/dev-tips/
Cheatsheet
JavaScript Testing
- Mocha Tests
- Chai
- Mocha - the fun, simple, flexible JavaScript test framework
- Sinon.JS - Standalone test fakes, spies, stubs and mocks for JavaScript. Works with any unit testing framework.
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
})();
- Use Cases for JavaScript's IIFEs — Marius Schulz
- An Introduction to IIFEs - Immediately Invoked Function Expressions - A Drip of JavaScript
Prototyp
Classes
CORS and fetch
if control over host server, do this
# Add these three lines to CORSify your server for everyone.
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
else find a CORS Proxy