Remove Duplicates from an Array
Compiled by Svein Petter Gjøby: const array = [1, 1, 1, 3, 3, 2, 2]; // Method 1: Using a Set const unique = [...new Set(array)]; // Method 2: Array.prototype.reduce const unique =...
View ArticleRequired Parameters for Functions in JavaScript
Ooo this is clever! I'm snagging this from David's blog. const isRequired = () => { throw new Error('param is required'); }; const hello = (name = isRequired()) => { console.log(`hello ${name}`)...
View ArticleGetting First and Last Items in Array (and splitting all the rest)
I needed to get the first item from an array lately in JavaScript. Hmmmm … lemme think here. I remember that .pop() is for snagging the last item from the array, like this: const arr = ["This",...
View ArticleInject HTML From a String of HTML
Say you have some HTML that is a string: let string_of_html = ` <div>Cool</div> `; Maybe it comes from an API or you've constructed it yourself from template literals or something. You can...
View ArticleThe .classList() API
Assuming you have an element in the DOM: <div id="el"></div> Get a reference to that DOM element: const el = document.querySelector("#el"); Then you can manipulate the classes on that...
View Article