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