👉 List of all notes for this book. IMPORTANT UPDATE November 18, 2024: I've stopped taking detailed notes from the book and now only highlight and annotate directly in the PDF files/book. With so many books to read, I don't have time to type everything. In the future, if I make notes while reading a book, they'll contain only the most notable points (for me).
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(){...}()