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!
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...`);
}
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!`);
}
}
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;
}
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!
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!
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];
}
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