<aside> ⚠️ This note serves as a reminder of the book's content, including additional research on the mentioned topics. It is not a substitute for the book. Most images are sourced from the book or referenced.
</aside>
Attention: decisions and patterns we apply across the whole program.
→ Exposing min necessary, keeping everying else as private as possible.
In order to block the variable to the block scope, use let
or const
, don’t use var
!
function diff(x, y) {
console.log(tmp); // ReferenceError with "const" and "let", undefined with "var"
if (x > y) {
const tmp = x; // or let or var
x = y;
y = tmp;
}
return y - x;
}
Use let
or const
to block the scope to lowest level but how to hide var
or function
too?
Hide var
by wrapping it by a function
.
var cache = {} // will be in the global scope
function factorial(x) {
if (x < 2) return 1; if (!(x in cache)) {
cache[x] = x * factorial(x - 1);
}
return cache[x];
}
factorial(6); // 720
// outer scope
function hideTheCache() {
// middle scope
var cache = {}
function factorial(x) {
if (x < 2) return 1; if (!(x in cache)) {
cache[x] = x * factorial(x - 1);
}
return cache[x];
}
}
var factorial = hideTheCache();
factorial(6); // 720
var factorial = (function hideTheCache() {
var cache = {}
function factorial(x) {
if (x < 2) return 1; if (!(x in cache)) {
cache[x] = x * factorial(x - 1);
}
return cache[x];
}
})() // () means "immediate invoke the function"
❇️ Invoking Function Expressions Immediately
The last ()
in the previous code is call Immediately Invoked Function Expression (IIFE). It’s useful to create a scropt to hide var/func.
// standalone IIFE -> "()" surround function is required
(function(){ .. })();
// with a name -> "()" surround function isn't required
(function namedIIFE(){ .. })();
function nameIIFE(){...}()