- Introduction
- Function Types & Patterns
- Scope & Closures
- Higher-Order Functions
- Projects
- Best Practices
- Performance Considerations
This repository provides production-ready implementations of JavaScript functions, scope management, closures, and higher-order functions. Each module includes practical examples, performance considerations, and real-world use cases.
- Function declarations vs expressions
- Arrow functions and
thisbinding - IIFE patterns for scope isolation
- Lexical scope vs dynamic scope
- Closure patterns and memory management
- Module patterns for encapsulation
- Higher-order function composition
- Functional programming principles
# Clone repository
git clone https://github.com/yourusername/js-functions-scope.git
# Navigate to directory
cd 01-functions-scope
# Run examples
node functions/function-declarations.js
# Run tests (if available)
npm test- Node.js β₯ 14.0.0
- Understanding of basic JavaScript syntax
- Modern code editor (VS Code recommended)
- Start with
functions/README.md - Practice with
scope-closures/ - Master
higher-order/ - Build
projects/
Each directory contains:
- README.md: Comprehensive guide
- .js files: Production-ready code with error handling
- Examples: Real-world use cases
- Performance tips: Optimization strategies
- Memory management with closures
- Debouncing and throttling patterns
- Currying and partial application
- Module federation patterns
- Tree-shaking optimizations
Each module includes testable patterns. Use Jest or Mocha for comprehensive testing.
MIT - See LICENSE file for details
- Fork the repository
- Create a feature branch
- Add comprehensive tests
- Submit a pull request
---
## π functions/
### π functions/README.md
```markdown
# π§ JavaScript Function Types: Production Patterns
## π Overview
Comprehensive guide to JavaScript function types with production-ready patterns, performance considerations, and best practices.
## π― Function Declarations vs Expressions
### Declaration (Hoisted)
```javascript
// β
Use for main logic, reusable functions
function calculateTotal(price, tax) {
return price * (1 + tax);
}
// β
Use for conditional assignments, callbacks
const calculateTotal = function(price, tax) {
return price * (1 + tax);
};// β
Short callbacks, array methods
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
// β
Lexical `this` binding
const user = {
name: 'John',
tasks: ['task1', 'task2'],
getTasks: function() {
return this.tasks.map(task => `${this.name}: ${task}`);
}
};// β Methods requiring `this` binding
const obj = {
value: 10,
// Avoid - no own `this`
increment: () => this.value++
};
// β Constructors
const Person = (name) => {
this.name = name; // Error: arrow functions can't be constructors
};// β
Isolate scope, avoid polluting global namespace
(function() {
const privateVar = 'secret';
// Logic here
})();// β
Module with public API
const UserModule = (function() {
let users = [];
const addUser = (user) => {
users.push(user);
return users;
};
const getUsers = () => [...users];
return { addUser, getUsers };
})();
// Usage
UserModule.addUser({ id: 1, name: 'John' });// β
Async initialization
(async function() {
const data = await fetchData();
initializeApp(data);
})();// Production pattern with error handling
const logger = {
log: function(level, message, metadata = {}) {
console[level](`[${new Date().toISOString()}] ${message}`, metadata);
}
};
// Context borrowing with safety
function safeLog(level, message) {
if (typeof console[level] !== 'function') {
level = 'log';
}
logger.log.call(logger, level, message, { context: this });
}
// Currying with bind
const logError = logger.log.bind(logger, 'error');
logError('Database connection failed');// β
Factory with validation
function createUser({ id, name, email }) {
if (!id || !name || !email) {
throw new Error('Missing required user properties');
}
if (!isValidEmail(email)) {
throw new Error('Invalid email format');
}
return {
id,
name,
email,
getProfile() {
return `${this.name} <${this.email}>`;
},
updateEmail(newEmail) {
if (isValidEmail(newEmail)) {
this.email = newEmail;
return true;
}
return false;
}
};
}
// Usage
const user = createUser({
id: 1,
name: 'Jane Doe',
email: 'jane@example.com'
});// β
Lazy evaluation, memory efficient
function* paginate(items, pageSize = 10) {
for (let i = 0; i < items.length; i += pageSize) {
yield items.slice(i, i + pageSize);
}
}
// Usage with large datasets
const largeDataset = Array.from({ length: 10000 }, (_, i) => i);
const paginator = paginate(largeDataset, 100);
for (const page of paginator) {
processPage(page); // Processes 100 items at a time
}function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
// Usage
const expensiveCalculation = memoize(function(n) {
console.log('Calculating...');
return n * 2;
});function debounce(func, wait, immediate = false) {
let timeout;
return function executedFunction(...args) {
const context = this;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
// Usage
const handleResize = debounce(() => {
updateLayout();
}, 250);| Feature | Declaration | Expression | Arrow |
|---|---|---|---|
| Hoisting | β Yes | β No | β No |
this binding |
Dynamic | Dynamic | Lexical |
| Arguments object | β Yes | β Yes | β No |
| Constructor | β Yes | β Yes | β No |
| Implicit return | β No | β No | β Yes |
- Use function declarations for main logic
- Use arrow functions for short callbacks
- Implement proper error handling
- Add input validation
- Consider memory usage with closures
- Add JSDoc comments for TypeScript
- Write unit tests for edge cases
- Test all function types
- Validate
thiscontext - Check error handling
- Verify return values
- Test with different inputs
- Arrow functions in constructors
- Memory leaks with closures
- Incorrect
thisbinding - Overuse of IIFEs
- Missing error handling