JavaScript Foundations
Day 2: Functions, Conditionals & Loops - Teaching JavaScript How to Think
Welcome to Day 2
Yesterday you learned how to store data in variables and perform basic calculations. But writing code line by line is limiting. Real programs need to make decisions, repeat tasks, and organize code into reusable blocks.
Today, you'll learn how to teach JavaScript to think. We'll cover functions (reusable code blocks), conditionals (making decisions), and loops (repeating actions). These are the tools that transform simple scripts into powerful programs.
Today's Goal: Master the three pillars of program logic. By the end of this lesson, you'll write functions that perform calculations, code that makes decisions based on conditions, and loops that automate repetitive tasks.
What You'll Build Today
Smart Calculator
Functions that add numbers, check if they're even, and return results
Grade Checker
Conditionals that determine Pass/Fail based on scores
Number Generator
Loops that count, calculate sums, and build sequences automatically
Functions: Reusable Code Blocks
Functions are like recipes. You write the instructions once, then use them whenever you need. They prevent repetition and make your code organized and maintainable.
Function Declaration
The traditional way to create a function using the function keyword.
// Function declaration function greet() { console.log("Hello, World!"); } // Call the function greet(); // Output: Hello, World! greet(); // Output: Hello, World! (reusable!)Visual Breakdown:
Step 1: Define the Function
function greet() { ... }
Function stored in memoryStep 2: Call the Function
greet();
Executes code inside function
Parameters and Arguments
Functions become powerful when they accept inputs. Parameters are placeholders; arguments are the actual values passed in.
// Function with parameters function greetUser(name) { console.log("Hello, " + name + "!"); } // Calling with different arguments greetUser("Alice"); // Output: Hello, Alice! greetUser("Bob"); // Output: Hello, Bob! // Multiple parameters function add(a, b) { console.log(a + b); } add(5, 3); // Output: 8 add(10, 20); // Output: 30How It Works:
add(5, 3);
a = 5b = 3Inside function:console.log(5 + 3);
Output: 8
Return Values
Functions can send data back using return. This makes them truly useful for calculations.
// Function that returns a value function multiply(x, y) { return x * y; } // Store the result let result = multiply(4, 5); console.log(result); // Output: 20 // Use directly in expressions console.log(multiply(3, 7) + 10); // Output: 31 // Multiple returns (conditional) function getMax(a, b) { if (a > b) { return a; } else { return b; } } console.log(getMax(10, 5)); // Output: 10 console.log(getMax(3, 8)); // Output: 8Key Concept:returnimmediately exits the function and sends the value back. Code afterreturnwon't run.
Arrow Functions (Modern Syntax)
A shorter, cleaner way to write functions. Perfect for simple operations.
// Traditional function function square(x) { return x * x; } // Arrow function (equivalent) const square = (x) => { return x * x; }; // Even shorter (implicit return) const square = x => x * x; // More examples const add = (a, b) => a + b; const greet = name => `Hello, ${name}!`; console.log(square(5)); // Output: 25 console.log(add(10, 20)); // Output: 30 console.log(greet("Alice")); // Output: Hello, Alice!Arrow Function Rules:
One parameter: Parentheses optional
x => x * 2Multiple parameters: Parentheses required
(a, b) => a + bSingle expression: Can omit braces and return
() => console.log("Hi")
Conditionals: Making Decisions
Conditionals let your code make choices. They check conditions and run different code based on whether those conditions are true or false.
if Statements
The simplest conditional. If the condition is true, run the code.
// Basic if statement let age = 20; if (age >= 18) { console.log("You are an adult."); } // With variables let temperature = 30; if (temperature > 25) { console.log("It's hot outside!"); }Visual Flow:
age = 20
if (age >= 18)Condition: 20 >= 18 is TRUE
Run the code inside!
if...else Statements
Provide an alternative when the condition is false.
// if...else let score = 45; if (score >= 50) { console.log("Pass"); } else { console.log("Fail"); } // Real-world example let isLoggedIn = false; if (isLoggedIn) { console.log("Welcome back!"); } else { console.log("Please log in."); }Decision Tree:
score >= 50 ?YES (true)
"Pass"NO (false)
"Fail"
if...else if...else Chains
Check multiple conditions in order.
// Multiple conditions let grade = 85; if (grade >= 90) { console.log("A"); } else if (grade >= 80) { console.log("B"); } else if (grade >= 70) { console.log("C"); } else if (grade >= 60) { console.log("D"); } else { console.log("F"); } // Time-based greeting let hour = 14; // 2 PM if (hour < 12) { console.log("Good morning!"); } else if (hour < 18) { console.log("Good afternoon!"); } else { console.log("Good evening!"); }Important: Conditions are checked top to bottom. As soon as one is true, that block runs and the rest are skipped. Order matters!
Comparison Operators in Conditionals
Common Operators:
===Strict equal to!==Strict not equal to>Greater than<Less than>=Greater than or equal<=Less than or equal// Combining conditions with && (AND) and || (OR) let age = 25; let hasLicense = true; if (age >= 18 && hasLicense) { console.log("Can drive"); } if (age < 13 || age >= 65) { console.log("Discount applies"); }Loops: Repeating Code
Loops automate repetitive tasks. Instead of writing the same code 10 times, write it once and tell JavaScript to run it multiple times.
for Loops
The most common loop. Perfect when you know how many times to repeat.
// Basic for loop: print 1 to 5 for (let i = 1; i <= 5; i++) { console.log(i); } // Output: 1, 2, 3, 4, 5 // Print 1 to 10 for (let i = 1; i <= 10; i++) { console.log(i); } // Countdown for (let i = 5; i > 0; i--) { console.log(i); } // Output: 5, 4, 3, 2, 1for Loop Anatomy:
for (let i = 1; i <= 5; i++)1. Initialization:let i = 1
Start with i equal to 12. Condition:i <= 5
Keep running while i is less than or equal to 53. Increment:i++
Add 1 to i after each iterationwhile Loops
Use when you don't know how many iterations you need – just keep going while a condition is true.
// Basic while loop let count = 1; while (count <= 5) { console.log(count); count++; } // User input simulation let attempts = 3; while (attempts > 0) { console.log("Attempts remaining: " + attempts); attempts--; } // Infinite loop prevention let number = 0; while (number < 100) { number = number + 10; console.log(number); }Warning: Always ensure the condition eventually becomes false, or you'll create an infinite loop that crashes the browser!Loop Control: break and continue
// break: exit the loop early for (let i = 1; i <= 10; i++) { if (i === 5) { break; // Stop at 5 } console.log(i); } // Output: 1, 2, 3, 4 // continue: skip to next iteration for (let i = 1; i <= 5; i++) { if (i === 3) { continue; // Skip 3 } console.log(i); } // Output: 1, 2, 4, 5Practical Loop Patterns
// Sum all numbers from 1 to 10 let sum = 0; for (let i = 1; i <= 10; i++) { sum = sum + i; } console.log(sum); // Output: 55 // Multiplication table for (let i = 1; i <= 5; i++) { console.log("5 x " + i + " = " + (5 * i)); } // Even numbers only for (let i = 2; i <= 10; i += 2) { console.log(i); } // Output: 2, 4, 6, 8, 10Practical Examples
Let's combine everything you've learned into practical, reusable code.
Example 1: Add Two Numbers Function
// Function to add two numbers function addNumbers(a, b) { return a + b; } // Test the function console.log(addNumbers(5, 3)); // Output: 8 console.log(addNumbers(10, 20)); // Output: 30 console.log(addNumbers(-5, 5)); // Output: 0 // Arrow function version const add = (a, b) => a + b;Example 2: Check if Number is Even
// Check if number is even function isEven(number) { return number % 2 === 0; } // Test the function console.log(isEven(4)); // Output: true console.log(isEven(7)); // Output: false console.log(isEven(0)); // Output: true console.log(isEven(13)); // Output: false // Using in a conditional let num = 24; if (isEven(num)) { console.log(num + " is even"); } else { console.log(num + " is odd"); }How It Works:
Modulo Operator (%): Returns the remainder of division
4 % 2 = 0(even)
7 % 2 = 1(odd)Example 3: Print Numbers 1–10
// Using for loop function printOneToTen() { for (let i = 1; i <= 10; i++) { console.log(i); } } printOneToTen(); // Using while loop function printOneToTenWhile() { let i = 1; while (i <= 10) { console.log(i); i++; } }Mini Challenge: Pass/Fail Checker
// Check if score is passing (>= 50) function checkPass(score) { if (score >= 50) { return "Pass"; } else { return "Fail"; } } // Or shorter with ternary operator const checkPass = score => score >= 50 ? "Pass" : "Fail"; // Test cases console.log(checkPass(75)); // Output: Pass console.log(checkPass(50)); // Output: Pass console.log(checkPass(49)); // Output: Fail console.log(checkPass(30)); // Output: FailChallenge Extension:
// Extended version with letter grades function getGrade(score) { if (score >= 90) return "A"; if (score >= 80) return "B"; if (score >= 70) return "C"; if (score >= 60) return "D"; return "F"; }Practical Exercises: Build Your Skills
Create a file called
day2-practice.jsand complete these exercises.Exercise 1: Calculator Functions
Task: Create functions for basic math operations.
// Exercise 1: Calculator Functions function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } function multiply(a, b) { return a * b; } function divide(a, b) { if (b === 0) { return "Cannot divide by zero"; } return a / b; } // Test your functions console.log("10 + 5 =", add(10, 5)); console.log("10 - 5 =", subtract(10, 5)); console.log("10 * 5 =", multiply(10, 5)); console.log("10 / 5 =", divide(10, 5)); console.log("10 / 0 =", divide(10, 0));Expected Output:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
10 / 0 = Cannot divide by zeroExercise 2: Number Analyzer
Task: Create a function that analyzes a number and returns information about it.
// Exercise 2: Number Analyzer function analyzeNumber(num) { let result = "Number: " + num + "\n"; // Check if even or odd if (num % 2 === 0) { result += "Type: Even\n"; } else { result += "Type: Odd\n"; } // Check if positive, negative, or zero if (num > 0) { result += "Sign: Positive"; } else if (num < 0) { result += "Sign: Negative"; } else { result += "Sign: Zero"; } return result; } console.log(analyzeNumber(7)); console.log("---"); console.log(analyzeNumber(-4)); console.log("---"); console.log(analyzeNumber(0));Expected Output:
Number: 7
Type: Odd
Sign: Positive
---
Number: -4
Type: Even
Sign: Negative
---
Number: 0
Type: Even
Sign: ZeroExercise 3: FizzBuzz Classic
Task: Print numbers 1–20, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for both.
// Exercise 3: FizzBuzz for (let i = 1; i <= 20; i++) { if (i % 3 === 0 && i % 5 === 0) { console.log("FizzBuzz"); } else if (i % 3 === 0) { console.log("Fizz"); } else if (i % 5 === 0) { console.log("Buzz"); } else { console.log(i); } }Expected Output:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, BuzzExercise 4: Sum of Range
Task: Create a function that calculates the sum of all numbers from 1 to n.
// Exercise 4: Sum of Range function sumToN(n) { let sum = 0; for (let i = 1; i <= n; i++) { sum += i; } return sum; } // Test console.log("Sum to 5:", sumToN(5)); // 15 (1+2+3+4+5) console.log("Sum to 10:", sumToN(10)); // 55 console.log("Sum to 100:", sumToN(100)); // 5050Exercise 5: Password Validator
Task: Check if a password meets criteria (at least 8 characters).
// Exercise 5: Password Validator function validatePassword(password) { if (password.length >= 8) { return "Password accepted"; } else { return "Password must be at least 8 characters"; } } // Test console.log(validatePassword("hello123")); // Accepted console.log(validatePassword("hi")); // Too short console.log(validatePassword("mypassword")); // AcceptedComplete Practice File
// =================================== // JavaScript Day 2: Practice Exercises // =================================== console.log("=== Exercise 1: Calculator ==="); function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } function multiply(a, b) { return a * b; } function divide(a, b) { return b === 0 ? "Cannot divide by zero" : a / b; } console.log("10 + 5 =", add(10, 5)); console.log("10 / 0 =", divide(10, 0)); console.log(""); console.log("=== Exercise 2: Number Analyzer ==="); function analyzeNumber(num) { let type = num % 2 === 0 ? "Even" : "Odd"; let sign = num > 0 ? "Positive" : num < 0 ? "Negative" : "Zero"; return `Number: ${num}, Type: ${type}, Sign: ${sign}`; } console.log(analyzeNumber(7)); console.log(analyzeNumber(-4)); console.log(""); console.log("=== Exercise 3: FizzBuzz ==="); for (let i = 1; i <= 20; i++) { if (i % 15 === 0) console.log("FizzBuzz"); else if (i % 3 === 0) console.log("Fizz"); else if (i % 5 === 0) console.log("Buzz"); else console.log(i); } console.log(""); console.log("=== Exercise 4: Sum to N ==="); function sumToN(n) { let sum = 0; for (let i = 1; i <= n; i++) sum += i; return sum; } console.log("Sum to 10:", sumToN(10)); console.log(""); console.log("=== Exercise 5: Password Validator ==="); const validatePassword = pwd => pwd.length >= 8 ? "Password accepted" : "Password too short"; console.log(validatePassword("hello123")); console.log(validatePassword("hi")); console.log(""); console.log("=== Bonus: Grade Checker ==="); const checkGrade = score => { if (score >= 90) return "A"; if (score >= 80) return "B"; if (score >= 70) return "C"; if (score >= 60) return "D"; return "F"; }; console.log("Score 85:", checkGrade(85)); console.log("Score 45:", checkGrade(45));Testing Your Code
Step 1: Create day2-practice.js fileStep 2: Copy the complete code aboveStep 3: Link in HTML:<script src="day2-practice.js"></script>Step 4: Open browser and check console (F12)Step 5: Modify values and experiment!Learn this with a real instructor
Free lessons take you a long way on your own. The full programmes add live classes, assignments, Skill Points and a certificate — built for African students.