Class-6-Introduction-to-Programming-Paradigms-min.pdf

srsalari 1 views 46 slides Oct 27, 2025
Slide 1
Slide 1 of 46
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46

About This Presentation

JavaScript Development Paradigm


Slide Content

Class 6: Introduction to
Programming Paradigms
5 Hours Total

Welcome to Day 6!
Two Ways to Organize Your Code
Quick Recap:
✅ Made pages interactive with events
✅ Handled user input
✅ Built interactive features
Today's Mission:
Learn the basics of Object-Oriented and Functional Programming!

Today's Learning Objectives
ª Create Objects
Learn about objects and classes
o Write Better Functions
Pure functions and avoiding bugs
© Compare Approaches
When to use objects vs functions
- Practice Both
Simple real-world examples
ä Think Clearly
Organize code better

SESSION 1: OBJECT-
ORIENTED
PROGRAMMING
(2 Hours)

What is a Programming Paradigm?
Different Ways to Organize Code
Think of it like organizing your room:
Object-Oriented: Group things by what they are (all clothes in
closet, all books on shelf)
Functional: Group things by what you do with them (morning
routine items together)
// Object-Oriented: Things that belong together
const car = {
brand: "Toyota",
color: "blue",
start: function() {
console.log("Car started!");
}
};
// Functional: Actions you perform
function calculateTotal(price, tax) {
return price + (price * tax);
}

Understanding Objects
Objects = Things with Properties and Actions
Think of objects like real-world things:
// A person object
const person = {
// Properties (characteristics)
name: "Alice",
age: 25,
job: "Developer",

// Methods (things they can do)
greet: function() {
console.log("Hi, I'm " + this.name);
},
haveBirthday: function() {
this.age = this.age + 1;
console.log("Now I'm " + this.age + " years old!");
}
};
// Using the object
person.greet(); // "Hi, I'm Alice"
person.haveBirthday(); // "Now I'm 26 years old!"
Key Points:
Objects group related data and functions together
this refers to the current object
Makes code more organized

Introduction to Classes
Classes = Blueprints for Objects
// A class is like a template
class Person {
// Constructor sets up new objects
constructor(name, age) {
this.name = name;
this.age = age;
}

// Methods define what objects can do
greet() {
console.log(`Hello, I'm ${this.name}!`);
}

haveBirthday() {
this.age++;
console.log(`Happy birthday! Now ${this.age} years old.`);
}
}
// Creating objects from the class
const alice = new Person("Alice", 25);
const bob = new Person("Bob", 30);
alice.greet(); // "Hello, I'm Alice!"
bob.haveBirthday(); // "Happy birthday! Now 31 years old."
Why Use Classes?
Create many similar objects easily
Keep code organized
Reuse code

Building a Simple Class
Let's Build a Car Class:
class Car {
constructor(brand, model, color) {
this.brand = brand;
this.model = model;
this.color = color;
this.speed = 0;
}

start() {
console.log(`The ${this.color} ${this.brand} is starting...`);
}

accelerate() {
this.speed += 10;
console.log(`Speed is now: ${this.speed} mph`);
}
}

Car Class (continued)
brake() {
if (this.speed > 0) {
this.speed -= 10;
console.log(`Slowing down to: ${this.speed} mph`);
}
}
getInfo() {
return `${this.color} ${this.brand} ${this.model}`;
}
}
// Using our Car class
const myCar = new Car("Toyota", "Camry", "blue");
myCar.start(); // "The blue Toyota is starting..."
myCar.accelerate(); // "Speed is now: 10 mph"
myCar.brake(); // "Slowing down to: 10 mph"

Extending Classes (Inheritance)
Creating Specialized Classes
// Base class - general animal
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}

eat() {
console.log(`${this.name} is eating.`);
}

sleep() {
console.log(`${this.name} is sleeping.`);
}
}

Inheritance Example
// Dog class extends Animal
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age); // Call parent constructor
this.breed = breed;
}

bark() {
console.log("Woof! Woof!");
}
}
// Usage
const myDog = new Dog("Buddy", 3, "Golden Retriever");
myDog.eat(); // "Buddy is eating." (from Animal)
myDog.bark(); // "Woof! Woof!" (from Dog)
Why Inheritance?
Reuse code from parent class
Create specialized versions
Keep related classes organized

Practical OOP Example - Game Characters
Let's Build a Simple Game!
// Player class for our game
class Player {
constructor(name, health = 100) {
this.name = name;
this.health = health;
this.score = 0;
this.items = [];
}

takeDamage(amount) {
this.health -= amount;
if (this.health <= 0) {
this.health = 0;
console.log(`${this.name} has been defeated!`);
}
}

collectItem(item) {
this.items.push(item);
this.score += 10;
console.log(`${this.name} collected ${item}!`);
}
}

Game Example (continued)
// Enemy class
class Enemy {
constructor(type, damage = 10) {
this.type = type;
this.damage = damage;
}

attack(player) {
console.log(`${this.type} attacks!`);
player.takeDamage(this.damage);
}
}
// Game in action
const hero = new Player("Hero");
const goblin = new Enemy("Goblin", 15);
hero.collectItem("Sword");
goblin.attack(hero);
console.log(`Health: ${hero.health}, Score: ${hero.score}`);

OOP Exercise - Build a Store
Product Class
class Product {
constructor(name, price, quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}

sell(amount = 1) {
if (this.quantity >= amount) {
this.quantity -= amount;
return true;
}
return false;
}
}

Store Class
class Store {
constructor(name) {
this.name = name;
this.products = [];
this.revenue = 0;
}
addProduct(product) {
this.products.push(product);
}
sellProduct(productName) {
const product = this.products.find(p => p.name === productName);
if (product && product.sell()) {
this.revenue += product.price;
return true;
}
return false;
}
}

Try It Yourself!
// Create your store
const myStore = new Store("Tech Shop");
myStore.addProduct(new Product("Laptop", 999, 5));
myStore.addProduct(new Product("Mouse", 25, 20));
// Make some sales
myStore.sellProduct("Laptop");
console.log(`Revenue: $${myStore.revenue}`);
Your Turn:
1Add a discount method
2Track customer purchases
3Show inventory status

OOP Summary
What We Learned About Objects & Classes
✅ Objects group related data and functions
✅ Classes are templates for creating objects
✅ Constructor sets up new objects
✅ Methods define what objects can do
✅ Inheritance lets classes extend other classes
When to Use OOP?
Building games (players, enemies, items)
Managing user interfaces (buttons, forms)
Modeling real-world things (products, users)
When you have "things" that do "actions"

Quick OOP Practice
Let's Practice Together!
// Build a simple Bank Account
class BankAccount {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}

deposit(amount) {
this.balance += amount;
console.log(`New balance: $${this.balance}`);
}
}
// Students: Add a withdraw method!

Quick OOP Practice
Let's Create a Todo List!
class TodoList {
constructor(name) {
this.name = name;
this.todos = [];
}
addTodo(task) {
const todo = {
id: Date.now(),
task: task,
completed: false
};
this.todos.push(todo);
console.log(`Added: ${task}`);
}
completeTodo(id) {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.completed = true;
console.log(`Completed: ${todo.task}`);
}
}
showTodos() {
console.log(`\n${this.name}:`);
this.todos.forEach(todo => {
const status = todo.completed ? "✓" : "○";
console.log(`${status} ${todo.task}`);
});
}
}
// Using our TodoList
const myTodos = new TodoList("Monday Tasks");
myTodos.addTodo("Learn JavaScript OOP");
myTodos.addTodo("Build a project");
myTodos.addTodo("Take a break");
myTodos.completeTodo(myTodos.todos[0].id);
myTodos.showTodos();

OOP Mini-Project
Build a Simple Banking System
class BankAccount {
constructor(owner, initialDeposit = 0) {
this.owner = owner;
this.balance = initialDeposit;
this.transactions = [];

if (initialDeposit > 0) {
this.addTransaction("deposit", initialDeposit);
}
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
this.addTransaction("deposit", amount);
console.log(`Deposited $${amount}. New balance: $${this.balance}`);
return true;
}
console.log("Invalid deposit amount");
return false;
}
withdraw(amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
this.addTransaction("withdrawal", amount);
console.log(`Withdrew $${amount}. New balance: $${this.balance}`);
return true;
}
console.log("Insufficient funds or invalid amount");
return false;
}
addTransaction(type, amount) {
this.transactions.push({
type: type,
amount: amount,
date: new Date().toLocaleString(),
balance: this.balance
});
}
getStatement() {
console.log(`\n=== Account Statement for ${this.owner} ===`);
console.log(`Current Balance: $${this.balance}`);
console.log("\nRecent Transactions:");
this.transactions.slice(-5).forEach(t => {
console.log(`${t.date} - ${t.type}: $${t.amount}`);
});
}
}
// Using the bank account
const myAccount = new BankAccount("John Doe", 1000);
myAccount.deposit(500);
myAccount.withdraw(200);
myAccount.deposit(150);
myAccount.withdraw(2000); // This will fail
myAccount.getStatement();

OOP Mini-Project (continued)
// Using the bank account
const myAccount = new BankAccount("John Doe", 1000);
myAccount.deposit(500);
myAccount.withdraw(200);
myAccount.deposit(150);
myAccount.withdraw(2000); // This will fail
myAccount.getStatement();
Challenge:
1Add a transfer method to send money between accounts
2Add interest calculation
3Create different account types (Savings, Checking)

BREAK TIME: 15
Minutes
☕ Stretch and Refresh!

SESSION 2:
FUNCTIONAL
PROGRAMMING
(2 Hours)

What is Functional Programming?
Writing Clean Functions
Functional programming focuses on writing functions that:
Take inputs and return outputs
Don't change things outside the function
Are predictable and easy to test
// Object-Oriented Style
class Calculator {
constructor() {
this.result = 0;
}

add(x) {
this.result += x; // Changes internal state
return this.result;
}
}
// Functional Style
function add(a, b) {
return a + b; // Just returns a value, doesn't change anything
}
const sum = add(5, 3); // Always returns 8
Key Ideas:
Functions should do one thing well
Avoid changing data - create new data instead
Make functions predictable

Pure Functions
Functions That Don't Have Side Effects
A pure function:
Always returns the same output for the same input
Doesn't change anything outside itself
Doesn't depend on anything that might change
Why Pure Functions?
Easier to test
Fewer bugs
Can run in any order
Easy to understand
// Not Pure - Changes external variable
let score = 0;
function addPoints(points) {
score += points; // Changes score outside function
return score;
}
// Pure - Only uses its inputs
function calculateScore(currentScore, points) {
return currentScore + points; // Returns new value
}
// Not Pure - Unpredictable
function rollDice() {
return Math.floor(Math.random() * 6) + 1; // Random!
}
// Pure - Predictable
function addDice(dice1, dice2) {
return dice1 + dice2; // Always same result
}
// Not Pure - Changes the input
function sortNumbers(numbers) {
return numbers.sort(); // This changes the original array!
}
// Pure - Creates new array
function sortNumbersPure(numbers) {
return [...numbers].sort(); // Makes a copy first
}

Working with Data Without
Changing It
Create New Instead of Changing
// With Objects
const user = { name: "Alice", age: 30 };
// Changing the original
user.age = 31;
// Creating a new object
const updatedUser = { ...user, age: 31 };
console.log(user); // Still age: 30
console.log(updatedUser); // Now age: 31

Immutable Arrays
// With Arrays
const scores = [10, 20, 30];
// Methods that change the array
scores.push(40); // Changes original!
// Methods that create new arrays
const moreScores = [...scores, 40];
const doubled = scores.map(s => s * 2);
const high = scores.filter(s => s > 20);
// Practical Example
function addToCart(cart, item) {
return [...cart, item]; // New array
}

Array Methods - Your New Best
Friends
JavaScript's Built-in Functional Tools
const numbers = [1, 2, 3, 4, 5];
// map - Transform each item
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - Keep items that pass test
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// find - Get first match
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
Key Point:
Original array never changes!

Map - Transform Data
// MAP - Transform each item
const prices = [10, 20, 30];
const withTax = prices.map(price => price * 1.08);
console.log(withTax); // [10.8, 21.6, 32.4]
// Real example
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob"]

Filter - Select Data
// FILTER - Keep items that pass a test
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
// Real example
const adults = users.filter(user => user.age >= 30);
console.log(adults); // [{ name: "Bob", age: 30 }]

Reduce - Combine Data
// REDUCE - Combine into one value
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 21
// Find oldest user
const oldest = users.reduce((oldest, user) =>
user.age > oldest.age ? user : oldest
);
Visual Guide:
MAP
[1,2,3] --(*2)--> [2,4,6]
FILTER
[1,2,3,4] --(even?)--> [2,4]
REDUCE
[1,2,3,4] --(sum)--> 10

Chaining Array Methods
Combining Methods for Power!
// Start with data
const employees = [
{ name: "Alice", dept: "Eng", salary: 95000 },
{ name: "Bob", dept: "Sales", salary: 75000 },
{ name: "Charlie", dept: "Eng", salary: 105000 }
];
// Chain methods together
const engineeringTotal = employees
.filter(emp => emp.dept === "Eng")
.map(emp => emp.salary)
.reduce((sum, sal) => sum + sal, 0);
console.log(engineeringTotal); // 200000

More Chaining Examples
// Get names of high earners
const highEarners = employees
.filter(emp => emp.salary > 80000)
.map(emp => emp.name)
.sort();
console.log(highEarners); // ["Alice", "Charlie"]

Functional Practice
Process Student Grades
const students = [
{ name: "Alice", grade: 85 },
{ name: "Bob", grade: 92 },
{ name: "Charlie", grade: 78 },
{ name: "Diana", grade: 95 }
];
// Get passing students (>= 80)
const passing = students
.filter(s => s.grade >= 80);
// Calculate average
const avg = students
.map(s => s.grade)
.reduce((sum, g) => sum + g, 0) / students.length;

Add Letter Grades
function getLetterGrade(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "D";
}
const withGrades = students.map(s => ({
...s,
letter: getLetterGrade(s.grade)
}));
// Honor roll (grade >= 90)
const honorRoll = students
.filter(s => s.grade >= 90)
.map(s => s.name);

Functional Programming Summary
What We Learned About Functional Programming
✅ Pure Functions - predictable, no side effects
✅ Immutability - create new data instead of changing
✅ Array Methods - map, filter, reduce
✅ Method Chaining - combine operations
✅ Clean Code - easier to test and understand
When to Use Functional Programming?
Processing lists of data
Calculations and transformations
When you need predictable results
Working with APIs and data
Avoiding bugs from shared state

Quick FP Practice
Let's Process Some Data!
const sales = [
{ product: "Laptop", amount: 1200 },
{ product: "Mouse", amount: 25 },
{ product: "Keyboard", amount: 75 }
];
// Together: Calculate total sales
const total = sales.reduce(
(sum, sale) => sum + sale.amount, 0
);
// Students: Get products over $50!

Shopping Cart Functions
Pure Functions in Action
const cart = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Mouse", price: 25 }
];
// Calculate total
function getTotal(items) {
return items.reduce(
(sum, item) => sum + item.price, 0
);
}
// Apply discount
function discount(items, percent) {
return items.map(item => ({
...item,
price: item.price * (1 - percent/100)
}));
}

Cart Operations
// Add item (new array)
function addItem(items, newItem) {
return [...items, newItem];
}
// Remove item (new array)
function removeItem(items, id) {
return items.filter(item => item.id !== id);
}
// Try it!
const total = getTotal(cart);
const withDiscount = discount(cart, 10);
const newCart = addItem(cart,
{ id: 3, name: "Keyboard", price: 75 }
);

BREAK TIME: 30
Minutes
¶ Lunch Break!

SESSION 3: CHOOSING
THE RIGHT APPROACH
(15 Minutes)

When to Use Which Approach?
Simple Guidelines
Use Objects/Classes When:
Building things that have properties and actions
Making games (players, enemies, items)
Creating UI components (buttons, forms)
You need to track state over time
Use Functional Style When:
Processing lists of data
Doing calculations
Transforming data from one format to another
You want predictable, bug-free code
Real World Examples:
// OOP: Good for a game character
class Player {
constructor(name) {
this.name = name;
this.health = 100;
}

takeDamage(amount) {
this.health -= amount;
}
}
// FP: Good for data processing
const grades = [85, 92, 78, 95];
const average = grades.reduce((sum, g) => sum + g, 0) / grades.length;

Combining Both Approaches
You Don't Have to Choose Just One!
Many real projects use both OOP and functional programming:
// Use a class for the main structure
class TodoApp {
constructor() {
this.todos = [];
}

// Use functional methods inside
addTodo(text) {
const newTodo = {
id: Date.now(),
text: text,
completed: false
};
// Create new array instead of mutating
this.todos = [...this.todos, newTodo];
}

// Functional approach for filtering
getActiveTodos() {
return this.todos.filter(todo => !todo.completed);
}

// Functional approach for counting
getStats() {
return {
total: this.todos.length,
completed: this.todos.filter(t => t.completed).length,
active: this.todos.filter(t => !t.completed).length
};
}
}
const app = new TodoApp();
app.addTodo("Learn JavaScript");
app.addTodo("Build a project");
console.log(app.getStats());
Best Practice:
Use OOP for structure, functional for data operations!

Final Exercise
Grade Tracker Challenge
class GradeTracker {
constructor(className) {
this.className = className;
this.students = [];
}

addStudent(name, grades) {
// TODO: Add student object
}

getClassAverage() {
// TODO: Use map and reduce
}

getPassingStudents() {
// TODO: Use filter (>= 70)
}
}

Test Your Code
// Test it!
const math101 = new GradeTracker("Math 101");
math101.addStudent("Alice", [85, 92, 88]);
math101.addStudent("Bob", [75, 68, 82]);
console.log(math101.getClassAverage());
console.log(math101.getPassingStudents());
Hints:
Store students as objects
Use functional methods
Don't mutate data

Homework Tasks
& Three Projects to Practice
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
this.available = true;
}
}
// TODO: Create Library class
// Use filter for searching
1. Library System 2. Grade Calculator
Calculate averages with reduce
Find top students with filter
Sort by grades
3. Todo App
Todo class with properties
Filter by status
Sort by date
Tags