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โฆ
# ๐ 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 will transform how you write JavaScript, making your code more predictable, reusable, and maintainable.
---
## ๐น Core Principles of Functional Programming
### 1. Pure Functions
### 2. Immutability
### 3. Function Composition
---
## ๐น First-Class Functions
### 1. Functions as Arguments
### 2. Returning Functions
### 3. Storing Functions
---
## ๐น Higher-Order Functions
### 1. Array Methods
### 2. Custom HOF Example
---
## ๐น Closures
Functions that remember their lexical scope.
### 1. Basic Closure
### 2. Practical Use Case
---
## ๐น Currying
Transforming a multi-argument function into a sequence of single-argument functions.
---
## ๐น Recursion
### 1. Basic Recursion
### 2. Tail Call Optimization
### 3. Recursive Array Processing
---
#JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions
Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that will transform how you write JavaScript, making your code more predictable, reusable, and maintainable.
---
## ๐น Core Principles of Functional Programming
### 1. Pure Functions
// Pure function (same input โ same output, no side effects)
function add(a, b) {
return a + b;
}
// Impure function (side effect + depends on external state)
let taxRate = 0.1;
function calculateTax(amount) {
return amount * taxRate; // Depends on external variable
}
### 2. Immutability
// Bad (mutates original array)
const addToCart = (cart, item) => {
cart.push(item); // Mutation!
return cart;
};
// Good (returns new array)
const addToCartFP = (cart, item) => [...cart, item];
### 3. Function Composition
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const toUpperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const shout = compose(exclaim, toUpperCase);
shout('hello'); // "HELLO!"
---
## ๐น First-Class Functions
### 1. Functions as Arguments
const numbers = [1, 2, 3];
// Passing function as argument
numbers.map(num => num * 2); // [2, 4, 6]
### 2. Returning Functions
const createMultiplier = factor => num => num * factor;
const double = createMultiplier(2);
double(5); // 10
### 3. Storing Functions
const mathOps = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
mathOps.add(3, 5); // 8---
## ๐น Higher-Order Functions
### 1. Array Methods
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Mouse', price: 25, inStock: false }
];
// Transform data
const productNames = products.map(p => p.name);
// Filter data
const availableProducts = products.filter(p => p.inStock);
// Reduce to single value
const totalPrice = products.reduce((sum, p) => sum + p.price, 0);
### 2. Custom HOF Example
function withLogging(fn) {
return (...args) => {
console.log(`Calling with args: ${args}`);
const result = fn(...args);
console.log(`Result: ${result}`);
return result;
};
}
const loggedAdd = withLogging(add);
loggedAdd(3, 5);---
## ๐น Closures
Functions that remember their lexical scope.
### 1. Basic Closure
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
counter(); // 1
counter(); // 2### 2. Practical Use Case
function createApiClient(baseUrl) {
return {
get(endpoint) {
return fetch(`${baseUrl}${endpoint}`).then(res => res.json());
},
post(endpoint, data) {
return fetch(`${baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(data)
});
}
};
}
const jsonPlaceholder = createApiClient('https://jsonplaceholder.typicode.com');
jsonPlaceholder.get('/posts/1').then(console.log);---
## ๐น Currying
Transforming a multi-argument function into a sequence of single-argument functions.
// Regular function
const add = (a, b, c) => a + b + c;
// Curried version
const curriedAdd = a => b => c => a + b + c;
curriedAdd(1)(2)(3); // 6
// Practical example
const createUser = username => email => password => ({
username,
email,
password
});
const registerUser = createUser('js_dev');
const withEmail = registerUser('[email protected]');
const finalUser = withEmail('secure123');
---
## ๐น Recursion
### 1. Basic Recursion
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}### 2. Tail Call Optimization
function factorial(n, acc = 1) {
return n <= 1 ? acc : factorial(n - 1, n * acc);
}### 3. Recursive Array Processing
function deepMap(arr, fn) {
return arr.map(item =>
Array.isArray(item) ? deepMap(item, fn) : fn(item)
);
}
deepMap([1, [2, [3]]], x => x * 2); // [2, [4, [6]]]---
โค1
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