Tutorial 3: Functions and Control Flow in JavaScript
What Are Functions in JavaScript?
A function is a block of code designed to perform a specific task. Functions make code reusable and organized, allowing you to call the same logic multiple times without rewriting it.
Syntax of a Function:
function functionName(parameters) {
// Code to be executed
}
Example of a Simple Function:
function greet() {
console.log("Hello, world!");
}
greet(); // Output: Hello, world!
Functions with Parameters and Return Values
Parameters: Functions can accept inputs (parameters) to process different data.
Return Values: Functions can send output back to the place where they were called.
Example with Parameters:
function add(a, b) {
console.log(a + b);
}
add(5, 3); // Output: 8
Example with a Return Value:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result); // Output: 20
Control Flow: Conditional Statements
Control flow determines the direction in which the program executes code based on conditions.
If Statements:
An if statement executes a block of code only if a specific condition is true.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
If-Else Statements:
let score = 70;
if (score >= 50) {
console.log("You passed!");
} else {
console.log("You failed.");
}
Else If for Multiple Conditions:
let grade = 85;
if (grade >= 90) {
console.log("Grade: A");
} else if (grade >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Loops in JavaScript
Loops allow you to execute a block of code repeatedly.
For Loop:
A for loop repeats code for a fixed number of iterations.
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
// Output: Count: 1, Count: 2, ..., Count: 5
While Loop:
A while loop continues to execute code as long as a condition is true.
let counter = 0;
while (counter < 3) {
console.log("Counter: " + counter);
counter++;
}
Combining Functions with Control Flow
Functions can use conditional logic and loops to solve more complex problems.
Example: Find the Larger of Two Numbers
function findMax(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
console.log(findMax(10, 15)); // Output: 15
Example: Sum of First N Numbers
function sumUpTo(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
console.log(sumUpTo(5)); // Output: 15
Practice Challenge: Simple Grade Calculator
Objective: Write a program that determines a student's grade based on their score.
Code Example:
function calculateGrade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else {
return "F";
}
}
console.log(calculateGrade(85)); // Output: B
Questions and Answers
Questions on Functions:
- Q: What is the purpose of a function in JavaScript?
- A: To create reusable blocks of code that perform specific tasks.
- Q: How do you call a function named greet ?
- A: Use greet ( ) ; .
Questions on Control Flow:
- Q: What does an if statement do?
- A: It executes a block of code if a condition is true.
- Q: How do you check multiple conditions in JavaScript?
- A: Use else if statements.
Questions on Loops:
Q: What is the difference between a for loop and a while loop?
- A: A for loop is used when the number of iterations is known, while a while loop is used when the condition is evaluated dynamically.
- Q: How do you stop a loop in JavaScript?
- A: Use the break statement.
Mini-Project: Multiplication Table
Objective: Create a program that generates a multiplication table for a given number.
Code Example:
function multiplicationTable(number) {
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
}
multiplicationTable(7);
// Output:
// 7 x 1 = 7
// 7 x 2 = 14
// ...
// 7 x 10 = 70
Conclusion
Recap:
- Functions simplify your code by making it reusable.
- Control flow ( if , else if , loops) determines the execution path of your code.
- Loops like for and while allow repeated execution of code blocks.
Next Steps: In the next tutorial, we’ll dive into Arrays and Objects, which are essential for organizing and working with data.
Additional Practice:
- Write a function to calculate the factorial of a number.
- Create a loop that prints all even numbers between 1 and 20.