Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Anonymous Functions and Callbacks

Congratulations on reaching the last lesson of Module 2! In this final stage, you will explore the power of anonymous functions and callbacks in JavaScript, tools that allow you to write more concise, flexible, and efficient code.

Anonymous Functions

Anonymous functions are like temporary workers hired to perform a specific task.

They are defined directly as arguments of other functions, without the need for a name. Imagine that you need to hire someone to paint your house.

You can hire a temporary painter who doesn’t have a specific name but knows exactly how to do the painting job.

In other words, anonymous functions are functions that do not have a name. They are declared at the moment they are used and are usually used as parameters for other functions.

Example:

setTimeout(function() {
     console.log("Executing anonymous function after 2 seconds.");
   }, 2000);

Callbacks

Callbacks are like messages left to be executed at a specific time.

They are passed as arguments to functions and will be called later, once a certain task is completed. Suppose you need to leave a message for a friend.

You leave the message with them and ask them to execute it when appropriate.

In other words, callbacks are functions passed as parameters to other functions and are called later by that function.

Example:

function performOperation(a, b, operation) {
     const result = operation(a, b);
     console.log("Result:", result);
   }

   function add(x, y) {
     return x + y;
   }

   performOperation(5, 3, add); // Output: Result: 8

Advantages:

  • Conciseness: Allows writing more concise and readable code.
  • Flexibility: Allows passing functionalities as parameters to other functions.
  • Efficiency: Helps avoid code duplication.

Challenge:

  1. Create a JavaScript script that prompts the user for a number.
  2. Create a function that checks whether the number is even or odd.
  3. Use an anonymous function as a callback to display a message on the screen indicating whether the number is even or odd.

Congratulations on completing Module 2! You have acquired advanced knowledge about functions in JavaScript.

Entrar na conversa
Rolar para cima