Data Analytics
# ๐ JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes #JavaScript #OOP #Prototypes #Classes #DesignPatterns Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-orientedโฆ
## ๐น Practical Example: Redux-like Store
---
## ๐น Best Practices
1. Strive for purity when possible
2. Limit side effects to controlled areas
3. Use immutable data with libraries like Immer
4. Compose small functions into larger ones
5. Document function signatures clearly
---
### ๐ What's Next?
In Part 9, we'll cover:
โก๏ธ Error Handling Strategies
โก๏ธ Debugging Techniques
โก๏ธ Performance Optimization
โก๏ธ Memory Management
#JavaScript #FunctionalProgramming #CleanCode ๐
Practice Exercise:
1. Convert an imperative function to pure FP style
2. Implement a
3. Create a memoization higher-order function
function createStore(reducer, initialState) {
let state = initialState;
const listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
};
return { getState, dispatch, subscribe };
}
// Reducer (pure function)
function counterReducer(state = 0, action) {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
}
// Usage
const store = createStore(counterReducer);
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' }); // Logs: 1---
## ๐น Best Practices
1. Strive for purity when possible
2. Limit side effects to controlled areas
3. Use immutable data with libraries like Immer
4. Compose small functions into larger ones
5. Document function signatures clearly
---
### ๐ What's Next?
In Part 9, we'll cover:
โก๏ธ Error Handling Strategies
โก๏ธ Debugging Techniques
โก๏ธ Performance Optimization
โก๏ธ Memory Management
#JavaScript #FunctionalProgramming #CleanCode ๐
Practice Exercise:
1. Convert an imperative function to pure FP style
2. Implement a
pipe() function (left-to-right composition) 3. Create a memoization higher-order function
Data Analytics
# ๐ JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript #JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts thatโฆ
# ๐ JavaScript Tutorial - Part 9/10: Error Handling & Debugging
#JavaScript #Debugging #ErrorHandling #Performance #BestPractices
Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance optimization strategies used by senior developers.
---
## ๐น Comprehensive Error Handling
### 1. Error Types in JavaScript
### 2. Custom Error Classes
### 3. Error Boundary Pattern (React-like)
---
## ๐น Advanced Debugging Techniques
### 1. Console Methods Beyond `log()`
### 2. Debugger Statement & Breakpoints
### 3. Source Maps in Production
---
## ๐น Performance Optimization
### 1. Benchmarking Tools
### 2. Memory Leak Detection
Common leak patterns:
### 3. Optimization Techniques
---
## ๐น Memory Management
### 1. Garbage Collection Basics
### 2. WeakMap & WeakSet
---
## ๐น Network Optimization
### 1. Bundle Analysis
### 2. Code Splitting
#JavaScript #Debugging #ErrorHandling #Performance #BestPractices
Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance optimization strategies used by senior developers.
---
## ๐น Comprehensive Error Handling
### 1. Error Types in JavaScript
try {
// Potential error code
} catch (error) {
if (error instanceof TypeError) {
console.log("Type error occurred");
} else if (error instanceof ReferenceError) {
console.log("Undefined variable");
} else if (error instanceof RangeError) {
console.log("Value out of range");
} else {
console.log("Unknown error:", error.message);
}
}### 2. Custom Error Classes
class ApiError extends Error {
constructor(url, status, message) {
super(`API call to ${url} failed with ${status}: ${message}`);
this.name = "ApiError";
this.status = status;
this.url = url;
}
}
// Usage
throw new ApiError("/users", 500, "Internal Server Error");### 3. Error Boundary Pattern (React-like)
function ErrorBoundary({ children }) {
const [error, setError] = useState(null);
try {
return children;
} catch (err) {
setError(err);
return <FallbackUI error={error} />;
}
}
// Wrap components
<ErrorBoundary>
<UnstableComponent />
</ErrorBoundary>---
## ๐น Advanced Debugging Techniques
### 1. Console Methods Beyond `log()`
console.table([{id: 1, name: 'Ali'}, {id: 2, name: 'Sarah'}]);
console.group("User Details");
console.log("Name: Ali");
console.log("Age: 25");
console.groupEnd();
console.time("API Call");
await fetchData();
console.timeEnd("API Call"); // Logs execution time### 2. Debugger Statement & Breakpoints
function complexCalculation() {
debugger; // Pauses execution here
// Step through with F10/F11
const result = /* ... */;
return result;
}### 3. Source Maps in Production
// webpack.config.js
module.exports = {
devtool: 'source-map', // Generates .map files
// ...
};
---
## ๐น Performance Optimization
### 1. Benchmarking Tools
// Using performance.now()
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log(`Operation took ${end - start}ms`);
### 2. Memory Leak Detection
Common leak patterns:
// 1. Accidental globals
function leak() {
leakedVar = 'This is global!'; // Missing var/let/const
}
// 2. Forgotten timers
const intervalId = setInterval(() => {}, 1000);
// Remember to clearInterval(intervalId)
// 3. Detached DOM references
const elements = [];
function storeElement() {
const el = document.createElement('div');
elements.push(el); // Keeps reference after removal
}
### 3. Optimization Techniques
// 1. Debounce rapid events
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// 2. Web Workers for CPU-intensive tasks
const worker = new Worker('task.js');
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);
// 3. Virtualize long lists (react-window, etc.)
---
## ๐น Memory Management
### 1. Garbage Collection Basics
// Circular reference (modern engines handle this)
let obj1 = {};
let obj2 = { ref: obj1 };
obj1.ref = obj2;
// Manual cleanup
let heavyResource = loadResource();
function cleanup() {
heavyResource = null; // Eligible for GC
}
### 2. WeakMap & WeakSet
const weakMap = new WeakMap();
let domNode = document.getElementById('node');
weakMap.set(domNode, { clicks: 0 });
// When domNode is removed, entry is automatically GC'd
---
## ๐น Network Optimization
### 1. Bundle Analysis
npm install -g source-map-explorer
source-map-explorer bundle.js
### 2. Code Splitting
// Dynamic imports
const module = await import('./heavyModule.js');
// React.lazy
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));