On gists
Self-Defining Functions
JavaScript
demo.js
Raw
#
// standard
/*
Boolean flags (let firstRun = true;)
Global state (if (!window.cachedResult) {...})
Unnecessary wrappers that make code harder to read
*/
let config;
function loadConfig() {
if (!config) {
console.log("Fetching config...");
config = { apiKey: "123", theme: "dark" };
}
return config;
}
console.log(loadConfig()); // Fetching config...
console.log(loadConfig()); // Still checks condition every time
// better
let loadConfig = function () {
console.log("Fetching config...");
const config = { apiKey: "123", theme: "dark" };
// Redefine itself
loadConfig = function () {
console.log("Returning cached config");
return config;
};
return config;
};
console.log(loadConfig()); // Fetching config...
console.log(loadConfig()); // Returning cached config
// anohter examples
let initClickHandler = function () {
console.log("Setting up click handler...");
document.body.addEventListener("click", () => {
console.log("Body clicked");
});
// Rewrite to a no-op
initClickHandler = function () {
console.log("Handler already set");
};
};
initClickHandler(); // Sets up handler
initClickHandler(); // Handler already set
let fetchUserData = function (id) {
console.log("Fetching user from API...");
const cache = {};
fetchUserData = function (id) {
if (cache[id]) return cache[id];
// Simulated fetch
return (cache[id] = { id, name: "User " + id });
};
return fetchUserData(id);
};
console.log(fetchUserData(1)); // Fetch + cache
console.log(fetchUserData(1)); // Cached
console.log(fetchUserData(2)); // New fetch