JS clipboard
Random js snippets – causing headaches or just stumbled upon while looking at the sun.
- Vars & Tenary
- document.ready equivalent
- selecting etc
- map, filter, reduce
- sorting sort()
- Getting the scroll position
- Optional Chaining (?.)
Vars & tenary
Setting a bool variableconst isAvailable = item.status === 'available' //bool
Tenary operator:condition ? trueVal : fasleVal
Examples
const volljaehrig = (age >= 18) ? "Ja" : Nein";return item ? item.name : 'the item';(if item is defined, return the item name, otherwse return ‚the item‘ instead
document.ready equivalent
document.addEventListener("DOMContentLoaded", function() {
// code...
});
selecting etc.
element.matches(selector) // returns bool
element.closest(selectors);
// example:
if( menuItem.matches(.active) ){
// menuItem has class 'active'
const nextMenuItem = menuItem.closest("li");
}
see: Element.matches(), Element.closest() at MDN
map, filter, reduce
map()
💡 [a,b,c] → [1,2,3]
Use it when: You want to translate/map all elements in an array to another set of values. [1]
// multiply all elements by 10
const numbers = [1,2,3]
const timesTen = array.map(number => number*10); // [10,20,30]
more details + all params see: Dan Martensen or MDN
filter()
💡 [a,b,c] → [a,c]
Use it when: You want to remove unwanted elements based on a condition. [1]
const data = ["a","","c"];
const notEmpty = data.filter(elem => "" !== elem); // ["a","c"]
more details + all params see: Dan Martensen or MDN
reduce()
💡 [1,2,3] → 6
Use it when: You want to find a cumulative [+] or concatenated value based on elements across the array. [1]
Arguments: (in Order) added value of last itterations, value of current itteration, (opt) index of itteration, (opt) original array invoking the method (??) and at the end the starting number
const numbers = [1,2,3]
const sum = numbers.reduce( (prevVal, currentVal) => prevVal + currentVal, 0 ); // 6
note that the prevVal is already the computed value of the previous iterations. If getting values from an object, e.g. person.age only the currentVal needs to access that property ( ... => prevVal + currentVal.age, 0 ). The first is already the sum of all previous ages.
sort()
💡 [3,1,2] → [1,2,3]
compares two items of the array at a time. If the comparing function returns 1, the current item is stacked on top of / listed before the second, if -1 is returned, the current item is stacked underneath / listed after.
const nums = [3,1,2,4];
const numsSorted = nums.sort( (a,b) => a > b ? 1 : -1 );
// [1,2,3,4,5]
note all of the methods above are chainable, eg:
const linksContainingOf = links
.map(el => el.textContent)
.filter(txt => txt.includes('of'));
more details + all params see: Dan Martensen or MDN
[1] Dan Martensen – JavaScript’s Map, Reduce, and Filter
Getting the scroll position
- scroll event:
scroll - scroll offset of an element:
element.scrollTop - global scroll position:
document.documentElement.scrollTop(sic.document.body.scrollTopis deprecated).
- or (browser support madness):
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0(soruce)
- or (browser support madness):
Optional Chaining
propertyKey?.
const users = [
{
name: "sxxm",
roles: {
canEdit: true,
canDelete: false
},
},
{
name: "g33k",
// has no roles {}
}
];
for (const user of users) {
console.log(user?.roles?.canEdit)
}
// Output:
// true
// undefined
Also checkout passive event listeners: https://stackoverflow.com/questions/37721782/what-are-passive-event-listeners#37721906