14.4 Anonymous Functions and Arrow Functions (15 mins)
Introduction to Anonymous Functions:
An anonymous function is a function without a name. These functions are often used when you need a function only once or want to pass a function as an argument to another function.
Example:
// Assigning an anonymous function to a variable const greet = function() { console.log("Hello, World!"); }; greet(); // Outputs: Hello, World!
Introduction to Arrow functions:
Arrow functions are a shorter syntax for writing functions introduced in ES6. They are especially useful for writing concise code.
Syntax:
(parameters) => { // Function body }Example:
const greet = () => { console.log("Hello, World!"); }; greet(); // Outputs: Hello, World!
Comparison with Regular Function Definitions:
Regular Function:
function add(a, b) { return a + b; } let result = add(5, 10); console.log(result); // Outputs: 15Anonymous Function (Assigned to a variable):
const add = function(a, b) { return a + b; }; let result = add(5, 10); console.log(result); // Outputs: 15Arrow Function:
const add = (a, b) => a + b; let result = add(5, 10); console.log(result); // Outputs: 15
Key Differences:
Shorter Syntax: Arrow functions are more concise and omit the
functionkeyword and curly braces{}when there's only one expression.No
thisBinding: Arrow functions do not have their ownthiscontext. This makes them useful in scenarios where you want to preserve thethiscontext from the surrounding code, such as in event handlers.Anonymous Nature: Both anonymous functions and arrow functions are often used in callbacks (e.g., in event listeners or array methods like
map()andforEach()).
Example Use Cases:
Anonymous Function in a Callback:
setTimeout(function() { console.log("This runs after 2 seconds"); }, 2000);Arrow Function in an Array Method:
let numbers = [1, 2, 3, 4]; let squared = numbers.map((num) => num * num); console.log(squared); // Outputs: [1, 4, 9, 16]
Student Activity (15 mins):
Objective: Students will define and use anonymous functions and arrow functions, comparing them to regular function declarations.
Step-by-Step Activity:
Create an HTML file (e.g.,
functions_anonymous_arrow.html) and write JavaScript code to demonstrate the use of anonymous and arrow functions.Example Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Anonymous and Arrow Functions</title> </head> <body> <h1>Check the Console for Function Outputs</h1> <script> // Regular function function multiply(a, b) { return a * b; } console.log("Multiply (Regular Function): " + multiply(3, 4)); // Outputs: 12 // Anonymous function assigned to a variable const divide = function(a, b) { return a / b; }; console.log("Divide (Anonymous Function): " + divide(10, 2)); // Outputs: 5 // Arrow function const subtract = (a, b) => a - b; console.log("Subtract (Arrow Function): " + subtract(10, 3)); // Outputs: 7 // Arrow function with no parameters const greet = () => console.log("Hello, World!"); greet(); // Outputs: Hello, World! // Arrow function with array method let numbers = [1, 2, 3, 4, 5]; let squared = numbers.map((num) => num * num); console.log("Squared Numbers (Arrow Function with map): " + squared); // Outputs: [1, 4, 9, 16, 25] </script> </body> </html>Run the file in a browser:
Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view the output of the anonymous and arrow functions.
Activity:
Step 1: Run the code and observe how each function (regular, anonymous, and arrow) works.
Step 2: Modify the functions:
Write an anonymous function that calculates the area of a circle (
πr²).Write an arrow function that converts a temperature from Celsius to Fahrenheit (
(C * 9/5) + 32).
Challenge:
Write an anonymous function inside
setTimeout()that prints a message after 3 seconds.setTimeout(function() { console.log("This message is displayed after 3 seconds"); }, 3000);Write an arrow function that filters out even numbers from an array.
let numbers = [1, 2, 3, 4, 5, 6]; let oddNumbers = numbers.filter((num) => num % 2 !== 0); console.log(oddNumbers); // Outputs: [1, 3, 5]
Activity Follow-up Questions:
What are the advantages of using arrow functions over regular functions?
In what situations might you prefer an anonymous function over a named function?
Can you think of a scenario where the difference in
thisbinding between regular functions and arrow functions would matter?
Expected Outcome:
Students will:
Understand how to define and use anonymous functions and arrow functions.
Compare the syntax and use cases for regular functions versus arrow functions.
Gain practical experience writing concise functions using the arrow function syntax.
Last updated