Javascript usage
1: use const when in a for loop (makes more readablefor (const myRow of Object2: start using querySelector and querySelectorAll
document.querySelectorAll('tag#.id or class').forEach( element => { console.log(element); } );3: when querying for selector, use the data attribute (notice [data-XXX=]):
document.getElementById('mark').querySelectorAll('smart-input[data-zyx="myVal"] input'))4: use setAttribute() and getAttribute() for data & value in any element
// stop using element.dataset.thisDataValue // use element.getAttribute('data-this-data-value');5: Use Boolean() to test null, zero, blank,etc
if ( Boolean(myValue) == true ) {
6: to use a variable value for an object tag, enclose the variable name inside of square brackets:
let myVar = 'mark'; let newObj = { [myVar] : 'this value' } ;7. Destructuring – there is a fast way to extract out an object element:
let myVar = thisObj.myVar; let {myVar} = thisObj ; // same as above but less typing.8. object mapping:
// Creates an array of objects with unique "name" property values. let uniqueObjArray = [ ...new Map(myObjArray.map( item => { const { keyToBeSkipped, anotherKeyToSkip, ...remainingItems} = item ; return [ JSON.stringify(remainingItems) , remainingItems] })).values(), ]; console.info( uniqueObjArray);https://yagisanatode.com/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/
https://plainenglish.io/blog/how-to-get-distinct-values-from-an-array-of-objects-in-javascript
https://www.geeksforgeeks.org/how-to-remove-a-key-from-javascript-object/
9. to manipulate a stylesheet:
const stylesheet = new CSSStyleSheet(); stylesheet.replaceSync('body { background-color: orange; }'); document.adoptedStyleSheets = [stylesheet];10. to extract out a value from an object, use object(DOT)find:
const frequency = values[0] ; ; const frequencyListAutoIncr = frequencyListObj.find( item => item.frequency == values[0]).frequencyListAutoIncr ;
11: debounce – see separate article on debounce
12: every() The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.and why it returns true for an empty array
const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold)); // Expected output: true
99: when leaving a promise, create a fake error then call it:
class ExitEarly extends Error { constructor(message) { super(message); this.name = “ExitEarly”; } } firstPromise.then(result => { if (/* time to exit early for whatever reason */) { throw new ExitEarly(‘Exiting after firstPromise’); } return secondPromise(result); })