By Jatinder Singh
📖 Table of Contents
- What Is a Smart Function?
- Higher-Order Functions
- Memoization
- Arrow Functions + Ternary Logic
- Function Currying
- Smart Initialization
- Context-Aware Functions
- Debounced or Throttled Functions
- Async Smart Functions
- Closures & Factory Functions
- Recap
- Final Thought
- About the Author
💡 What Is a Smart Function?
A smart function in JavaScript isn’t a built-in feature or official term. Instead, it’s a way developers refer to functions that are reusable, adaptive, and efficient.
🔁 Higher-Order Functions
function smartLogger(fn) {
return function (...args) {
console.log("Calling with:", args);
return fn(...args);
};
}
const add = (a, b) => a + b;
const loggedAdd = smartLogger(add);
console.log(loggedAdd(2, 3));
⚡ Memoization
function memoize(fn) {
const cache = {};
return function (...args) {
const key = JSON.stringify(args);
if (cache[key]) return cache[key];
const result = fn(...args);
cache[key] = result;
return result;
};
}
const smartFactorial = memoize(function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
});
🎯 Arrow Functions + Ternary Logic
const smartCheck = (val) => val ? "Exists" : "Missing";
🧱 Function Currying
const smartMultiply = (a) => (b) => a * b;
const double = smartMultiply(2);
console.log(double(5));
⚙️ Smart Initialization
const smartConfig = (() => {
const env = "dev";
return env === "prod" ? { debug: false } : { debug: true };
})();
🧠 Context-Aware Functions
function smartParser(input) {
if (typeof input === "string") return JSON.parse(input);
if (typeof input === "object") return JSON.stringify(input);
return input;
}
⏱️ Debounced or Throttled Functions
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
🌐 Async Smart Functions
const fetchDataSmart = async (url) => {
try {
const res = await fetch(url);
return await res.json();
} catch (e) {
return { error: "Failed to fetch" };
}
};
🔐 Closures & Factory Functions
function smartCounter() {
let count = 0;
return {
increment: () => ++count,
reset: () => (count = 0),
value: () => count,
};
}
const counter = smartCounter();
✅ Recap of Smart Function Patterns
| Pattern | Purpose |
|---|---|
| Higher-Order Functions | Extend behavior |
| Memoization | Cache results |
| Currying | Reuse with different inputs |
| Closures/Factories | Maintain private state |
| Debounce/Throttle | Optimize UI interactions |
| Async/Await + Try/Catch | Handle API or async errors smartly |
| Conditional Logic | Adapt to input types |