Lecture on Anonymous Functions in JavaScript
Anonymous functions are functions that do not have a name. They are commonly used as arguments to other functions or methods, such as in event handlers, callbacks, and immediately invoked function expressions (IIFEs).
They are a key part of functional programming and allow for concise and readable code.
### Why Use Anonymous Functions?
1. **Conciseness**: Anonymous functions provide a shorthand for defining functionality without the need for a separate named function, reducing verbosity.
2. **Encapsulation**: They are useful for encapsulating code that does not need to be reused elsewhere, keeping the global namespace clean.
3. **Higher-Order Functions**: They are often used with higher-order functions, such as `map`, `filter`, and `reduce`, where the function is passed as an argument.
### Example Usage
1. **Event Handlers**:
```javascript
document.getElementById("btn").addEventListener("click", function() {
console.log("Button clicked!");
});
```
2. **Callbacks**:
setTimeout(function() {
console.log("Time's up!");
}, 1000);
3. **Higher-Order Functions**:
```javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]
```
Lab: Working with Anonymous Functions
Objective
To understand and implement anonymous functions in various scenarios including:
event handling
callbacks
higher-order functions. (HOF)
Setup
1. Ensure you have a working JavaScript environment. You can use any modern browser or Node.js.
2. Create a new directory for your lab and open it in your code editor (e.g., Visual Studio Code).
Part 1: Event Handling with Anonymous Functions
1. **Create an HTML file (`index.html`)**:
<!DOCTYPE html>
<html>
<head>
<title>Anonymous Functions Lab</title>
</head>
<body>
<button id="btn">Click Me</button>
<script src="script.js"></script>
</body>
</html>
2. **Create a JavaScript file (`script.js`)**:
// Add event listener with an anonymous function
document.getElementById("btn").addEventListener("click", function() {
console.log("Button clicked!");
});
```
3. **Run the HTML file**:
- Open `index.html` in your browser.
- Click the button and observe the console output.
### Part 2: Using Anonymous Functions as Callbacks
1. **Create a JavaScript file (`callbacks.js`)**:
```javascript
// Using setTimeout with an anonymous function
setTimeout(function() {
console.log("Time's up!");
}, 1000);
// Using setInterval with an anonymous function
let count = 0;
const intervalId = setInterval(function() {
count++;
console.log(`Count: ${count}`);
if (count === 5) {
clearInterval(intervalId);
}
}, 1000);
```
2. **Run the JavaScript file**:
- If using Node.js, run the file in the terminal:
```sh
node callbacks.js
```
### Part 3: Higher-Order Functions with Anonymous Functions
1. **Create a JavaScript file (`higherOrderFunctions.js`)**:
```javascript
const numbers = [1, 2, 3, 4, 5];
// Using map with an anonymous function
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log("Doubled:", doubled); // [2, 4, 6, 8, 10]
// Using filter with an anonymous function
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log("Even Numbers:", evenNumbers); // [2, 4]
// Using reduce with an anonymous function
const sum = numbers.reduce(function(total, num) {
return total + num;
}, 0);
console.log("Sum:", sum); // 15
```
2. **Run the JavaScript file**:
- If using Node.js, run the file in the terminal:
```sh
node higherOrderFunctions.js
```
### Summary of Anonymous Functions
Anonymous functions are versatile and useful in many scenarios where a quick, one-time-use function is needed. They help to keep code concise and maintainable, especially when working with higher-order functions and event-driven programming.
### Knowledge Testing Activity
1. **Create a JavaScript file (`knowledgeTest.js`)**:
- Define an array of students with their names and grades.
- Use higher-order functions (`map`, `filter`, `reduce`) with anonymous functions to:
- Create an array of student names.
- Filter out students with grades above a certain threshold.
- Calculate the average grade of the students.
2. **Example Code**:
```javascript
const students = [
{ name: 'Alice', grade: 85 },
{ name: 'Bob', grade: 92 },
{ name: 'Charlie', grade: 78 },
{ name: 'David', grade: 88 },
{ name: 'Eve', grade: 91 }
];
// 1. Create an array of student names using map with an anonymous function
const studentNames = students.map(function(student) {
return student.name;
});
console.log("Student Names:", studentNames);
// 2. Filter out students with grades above 80 using filter with an anonymous function
const highGrades = students.filter(function(student) {
return student.grade > 80;
});
console.log("High Grades:", highGrades);
// 3. Calculate the average grade using reduce with an anonymous function
const totalGrades = students.reduce(function(total, student) {
return total + student.grade;
}, 0);
const averageGrade = totalGrades / students.length;
console.log("Average Grade:", averageGrade);
```
3. **Run the JavaScript file**:
- If using Node.js, run the file in the terminal:
```sh
node knowledgeTest.js
```
### Conclusion
This lab demonstrates the use of anonymous functions in various contexts such as event handling, callbacks, and higher-order functions. Understanding and effectively using anonymous functions is essential for writing concise and maintainable JavaScript code, particularly in functional programming and event-driven environments.