Tagged “syntax”
Sets in JavaScript
I don’t often store things in a Set
in JavaScript, but maybe I should. The fact it will only store unique values makes it pretty handy.
One place I do currently use a Set
is for the TagList
in my 11ty-based personal website. I start by defining TagList
as a new, empty Set
. I then need to assemble all possible tags so iterate blog posts and for each add its associated tags to TagList
. This means I can be sure that all duplicates will be removed automatically.
As you would imagine, Set
has built-in methods for adding, deleting and iterating items. But if you need to do something beyond that, you can easily turn it into an array, for example by:
const myArray = [...mySet];
Also, browser support is pretty good. So although to date I’ve been safely confining my use to Node scripts for building my static site, I could probably be using it client-side, too.
JavaScript Arrow Functions
JavaScript arrow functions are one of those bits of syntax about which I occasionally have a brain freeze. Here’s a quick refresher for those moments.
Differences between arrow functions and traditional functions
Arrow functions are shorter than traditional function syntax.
They don’t bind their own this
value. Instead, the this
value of the scope in which the function was defined is accessible. That makes them poor candidates for methods since this
won’t be a reference to the object the method is defined on. However it makes them good candidates for everything else, including use within methods, where—unlike standard functions—they can refer to (for example) this.name
just like their parent method because the arrow function has no overriding this
binding of its own.
TL;DR: typical usage
const doStuff = (foo) => {
// stuff that spans multiple lines
};
// short functions
const add = (num1, num2) => num1 + num2;
Explainer
// Traditional Function
function (a) {
return a + 100;
}
// Arrow Function Breakdown
// 1. Remove "function", place => between argument and opening curly
(a) => {
return a + 100;
}
// 2. Remove braces and word "return". The return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses
a => a + 100;
References
See all tags.