Javascript Snippets for you - #2
Edition 2 of me giving you essential JS snippets every week
Abhiraj Bhowmick
So how's it going?
Welcome to the 2nd edition of 50 essential JS snippets, you need to know,/
Let's get started.
1️⃣ allEqual
This snippet checks whether all elements of the array are equal.
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
2️⃣ approximatelyEqual
This snippet checks whether two numbers are approximately equal to each other, with a small difference.
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
3️⃣ attempt
This snippet executes a function, returning either the result or the caught error object.
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
4️⃣ bifurcateBy
This snippet splits values into two groups, based on a predicate function. If the predicate function returns a truthy value, the element will be placed in the first group. Otherwise, it will be placed in the second group.
You can use Array.prototype.reduce()and Array.prototype.push()to add elements to groups, based on the value returned by fnfor each element.
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');
// [ ['beep', 'boop', 'bar'], ['foo'] ]
5️⃣ bottomVisible
This snippet checks whether the bottom of a page is visible.
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
6️⃣ castArray
This snippet converts a non-array value into array.
castArray('foo'); // ['foo']
castArray([1]); // [1]
7️⃣ compact
This snippet removes false values from an array.
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]
8️⃣ currentURL
This snippet returns the current URL.
currentURL(); // 'https://abhiraj.mdx.one'
9️⃣ defer
This snippet delays the execution of a function until the current call stack is cleared.
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
🔟 degreesToRads
This code snippet can be used to convert a value from degrees to radians.
degreesToRads(90.0); // ~1.5708
Thank you for reading. Stay tuned for part 3.
Signup for my newsletter below to never miss out on my blogs and tech news.
Until next time,
Abhiraj
Upvote
Abhiraj Bhowmick
I make stuff on the web and write blogs about it.

Related Articles