Today I Learned - Rocky Kev

TIL Closures in Private Methods

POSTED ON:

TAGS:

In JS, closures are useful in hiding the implementation of functionality while still revealing the interface.

Note - it's using a IIFE

For example, imagine you are writing a class of date utility methods and you want to allow users to look up weekday names by index, but you don't want them to be able to modify the array of names you use under the hood.

const jediCatalog = {

getJediFromRank: (function() {

const rankTable = {
"jedi masters" : ["Yoda", "Obi-Wan Kenobi", "Mace Windu"],
"jedi knights" : ["Anakin Skywalker", "Luke Skywalker"],
"padawans" : ["Ahsoka Tano"]
}

return function(x) {
if ((typeof x !== 'string')) {
throw new Error("invalid type. Must be string");
}

if (rankTable.hasOwnProperty(x)) {
return rankTable[x];
} else {
throw new Error("Must be 'jedi masters', 'jedi knights', or 'padawans'")
}

};
}())
};


console.log(jediCatalog.getJediFromRank("jedi masters"));
// result:
// [object Array] (3)
// ["Yoda","Obi-Wan Kenobi","Mace Windu"]

The goal of getJediFromRank is to get Jedi based on their rank.

Why is rankTable inside the anonymous function?
It locks the connection of the data to the output, and scopes that data.

A developer can't just modify the jediCatalog object to change the rankTable. They would have to change it inside the anonymous function, which separates it's concern.

REFERENCE:
https://stackoverflow.com/a/2728628/4096078

SERIES:


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.