javascript #
Notes #
these notes are all over the place, needs organizing
“for of” loop
const numbers = [1,2,3,4]
for (let el of numbers){
console.log(el)
}
same output as above for of loop
numbers.forEach(function(el){
console.log(el)
})
you cannot make the connectedCallback of a web component async becuase it doesn’t match the function signature of the htmlelement class
- you can make an async render() function
when using .innerHTML is it dangerous and might allow for XSS, use .textContent
- does .textContent sanitize??
data-url html attributes are accessed with .dataset.url in js
attributeChangedCallback(prop, value), web component method
dont forget to import the web component classes in the app.js, or import tree
history.pushState(“null”,:"", “/fake-url”)
- will update the back and forward button because that cycles history statese
- pop state is back
a service worker is a web worker
- web workers are separate threads
- but a service worker can work as a proxy and local web server
- service worker stores requests and responses in the cache in the browser
- can create a separate cache section within the browswer cache
- this is separate from the network tab cache though
- service worker stores requests and responses in the cache in the browser
map, filter, reduce — quick explanation with examples #
map: transforms each item in an array into a new item, returning a new array of the same length.
Signature: arr.map((item, index, arr) => newValue)
Use when you need a 1:1 transformation.
Example:
const nums = [1,2,3]; const doubled = nums.map(n => n * 2); // [2,4,6]
filter: selects a subset of elements that satisfy a predicate, returning a new array (length ≤ original).
Signature: arr.filter((item, index, arr) => boolean)
Use when you need to keep only some elements.
Example:
const nums = [1,2,3,4]; const evens = nums.filter(n => n % 2 === 0); // [2,4]
reduce: folds the array into a single value (or object/array) by applying an accumulator function.
Signature: arr.reduce((accumulator, item, index, arr) => newAccumulator, initialValue)
Use when you need a single result (sum, product, grouped object, etc.).
Examples:
const nums = [1,2,3,4]; const sum = nums.reduce((acc, n) => acc + n, 0); // 10 // build an object grouping by parity const grouped = nums.reduce((acc, n) => { const key = (n % 2 === 0) ? 'even' : 'odd'; acc[key] = acc[key] || []; acc[key].push(n); return acc; }, {}); // { odd: [1,3], even: [2,4] }
Notes:
- map and filter do not mutate the original array (they return new arrays).
- reduce can return any type; be careful to provide an appropriate initialValue (if omitted, reduce uses the first array element as the initial accumulator).
- You can chain them: arr.filter(…).map(…).reduce(…). Use chaining for clarity but avoid unnecessary passes for performance-sensitive code.
Here are commonly used JavaScript array and utility methods worth knowing, grouped by purpose with short examples.
Array transformation & traversal
forEach: run side-effect for each element (returns undefined).
arr.forEach((x,i) => console.log(i, x));map, filter, reduce: (already covered)
Searching & testing
find: returns first element matching predicate.
const item = arr.find(x => x.id === 3);findIndex: index of first match (or -1).
some: true if any element satisfies predicate.
every: true if all elements satisfy predicate.
includes: true if array contains a value (uses SameValueZero).
[1,2,3].includes(2); // true
Sorting & ordering
sort: in-place sort with optional comparator.
arr.sort((a,b) => a.age - b.age);reverse: reverse array in place.
slice: return shallow copy subarray (non-mutating).
splice: mutate array to insert/remove items.
Combining & copying
concat: return new array by concatenation.
flat / flatMap: flatten nested arrays (flatMap maps then flattens one level).
arr.flat(2); arr.flatMap(x => x.items);spread (…) — shallow copy, combine arrays/objects.
const copy = [...arr]; const merged = [...a, ...b];
Array creation & inspection
- Array.from(iterable, mapFn?)
- Array.isArray(value)
- length property
Typed iteration / indices
- entries(): iterator of [index, value]
- keys(): iterator of indices
- values(): iterator of values
Object utilities
- Object.keys(obj), Object.values(obj), Object.entries(obj)
- Object.assign(target, …sources)
- structuredClone(obj) — deep clone (when available)
- Object.freeze / seal
Promises & async
- Promise.resolve / reject
- Promise.all, Promise.allSettled, Promise.race, Promise.any
- async/await (syntax; works with Promises)
String helpers
- trim, includes, startsWith, endsWith, split, replace (with regex or function), padStart/padEnd
Modern ES helpers
- optional chaining: obj?.prop?.[0]
- nullish coalescing: a ?? b (use b if a is null/undefined)
- nullish assignment: ??=
- logical assignment: ||=, &&=
- destructuring arrays/objects, default parameters, rest/spread
Miscellaneous useful APIs
- Map, Set, WeakMap, WeakSet
- Date, Intl (Intl.DateTimeFormat, Intl.NumberFormat)
- URL and URLSearchParams
- fetch (network requests) + AbortController
- localStorage / sessionStorage (browser)
- console.table for quick debugging
Performance & immutability tips
- Prefer methods that avoid unnecessary copies in hot code paths.
- Use immutable patterns (spread, map) for functional style; use in-place methods (push, splice, sort) when you need performance and understand side effects.
If you want, I can generate a one-page cheat sheet (grouped with short examples) tailored to your experience level (beginner/intermediate/advanced).
Code Snippets #
//show the keys of an object
Object.keys(obj)
pool = new Pool({
host: 'localhost',
database: 'postgres',
user:'postgres',
password:'mynewpassword',
port: 5432
});
express & ejs #
- the route for to find public depends on the nested routing js file…
- monies js routes need ../nav/nav.css and ../nav/nav.js instead of just nav/nav .. super fucking annoying
auth & session #
npm i passport-local
npm i express-session
npm i connect-flash
express session #
- requires express-session
- sessions are server side in memory / in database data that corresponds to a user, logged in or not, express-session sends a session id cookie to the browser and keeps track of cookie data for that use
- this will need to be upgraded to a real db in production
connect-flash #
passport #
hono #
- if there is an error starting deno because of a tsx error there probably is just a typo in the component
algorithms #
// javascript recursive factorial
function factorialize(num) {
if(num == 1 || num == 0){
return 1
} else {
return (num * factorialize(num-1))
}
return num;
}
factorialize(5);
// javascript bubble sort
function bubble_sort(arr){
for(let i=0; i < arr.length;i++){
for(let j = 0; j< arr.length - 1 - i; j++){
if (arr[j] > arr[j+1]){
const tmp = arr[j];
arr[j] = arr[j+1];
arr[j +1] = tmp;
}
}
}
}
// javascript recursive factorial
function factorialize(num) {
if(num == 1 || num == 0){
return 1
} else {
return (num * factorialize(num-1))
}
return num;
}
factorialize(5);