Just starting out with callback functions (using a callback as an argument)(Javascript)

Hello everyone,

I'm a beginner here and I have a question about callback functions. Upon reading about them, I felt like I understood the concept. However, when I attempted to implement one in my code, things didn't go as planned.

    function greeting (name, callback){
      console.log(`Greetings ${name}`);
      callback();
    };

    function timeOfDay (time){
      console.log(`How are you this fine ${time}?`);
    };

    greeting ('Brad', timeOfDay('evening') );

Here's the output:

How are you this evening?
Greetings Brad
Uncaught TypeError: callback is not a function

Could someone please help me understand why the output is in this particular order? What does the error mean, and why does it appear even though the code seems to have finished executing?

Previously, when I tried a simpler callback function with a similar structure, it worked without any issues.

Thank you all for your assistance! - Brad

Answer №1

You were getting close, but when you passed timeOfDay("evening"), it wasn't actually being passed as a callback function. Instead, it was immediately invoked and whatever value it returned (which in this case is nothing) was being passed to the greeting function. Since timeOfDay doesn't return anything, you ended up passing undefined to greeting.

The correct solution is to pass an actual function as the callback to greeting. One way to do this is by wrapping the timeOfDay() function call in an anonymous function like so:

function greeting(name, callback) {
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay(time) {
  console.log(`How are you this fine ${time}?`);
};

greeting('Brad', function() { timeOfDay('evening') });

Another approach is to use the Function.bind() method. This method creates a new function with the specified context for execution, which can be very useful but requires understanding of scope and context. You can learn more about this technique in another answer here:

function greeting(name, callback) {
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay(time) {
  console.log(`How are you this fine ${time}?`);
};

greeting('Brad', timeOfDay.bind(this, 'evening'));

Answer №2

According to the comments, in a situation like this:

greeting ('Brad', timeOfDay('evening') );

The timeOfDay function will be executed instantly.

To prevent this from happening, there are several options you can consider:

  1. Wrap your function call in an anonymous function, as mentioned in other responses.

  2. You can also remove the parentheses, like so: greeting('Brad', timeOfDay); (this will prevent immediate function execution, but you may lose the parameter "evening" and the error will persist).

  3. You can use .bind() to specify a context for the function. In the example below, I'm binding this as the context for the function to prevent instant execution.

Here is an example:

function greeting (name, callback){
  console.log(`Greetings ${name}`);
  callback();
};

function timeOfDay (time){
  console.log(`How are you this fine ${time}?`);
};

greeting ('Brad', timeOfDay.bind(this, 'evening') );

For more information, you can visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

What are the benefits of incorporating an external API with Next.js API routes?

I've recently started using Next.js and I'm curious about the purpose of export default function handler since we can directly fetch data from APIs. In my HTML code, I have the following snippet. When the submit button is clicked, the sendformDa ...

Issue with Bootstrap checkbox/switch

Trying to determine the status of a checkbox - whether it's checked or not. The default state is unchecked, but I need to perform actions when it is checked and also when it gets unchecked. Currently using bootstrap 5.3.0 alpha html <div clas ...

Execute command problem

Explaining this code may be a bit tricky, but I'll do my best. Below is the code snippet for executing a slash command. client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; const command = c ...

Once the form has been submitted, proceed to open a new page following processing

Trying to remove an entry or offer from the database and then return to the page with all entries/offers. Attempted using Javascript, but it successfully deletes the item without redirecting to the overview page. Is this the correct approach with Javascri ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

What is the best way to determine the variable height of a div in Angular 7?

I'm currently trying to use console.log in order to determine the height of a div based on the size of a table inside it. This information is crucial for me to be able to ascertain whether or not a scrollbar will be present, especially within a dialog ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

The change event for Bootstrap 4 switches is not functioning as expected

I am facing an issue with multiple Bootstrap 4 switches that are dynamically loaded onto the page using JS append. I need to call a function when the switch changes. The example below works fine when the switches are added in HTML, but it doesn't work ...

Personalized Jasmine matchers for a Protractor/WebDriverJS component

Greetings fellow developers, I'm looking to create a custom matcher for Protractor/WebDriverJS element. Can anyone assist in improving my current code? Here is what I aim to include in the specs files: var button = element(by.tagName('button&a ...

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

Concealing UI elements within the primary stack during navigation to a nested stack in React navigation

Is there a way to hide the user interface in my main stack when I switch to the nested drawer stack? I am currently facing an issue where the header from my main stack appears above the header in my nested stack when I navigate to a screen using: navigat ...

Having an issue with fastify-multer where request.files is coming back as undefined during testing with Postman

In the process of developing an API that consumes multipart/form-data using fastify, I've integrated the fastify-multer plugin to handle file uploads for passing them to another third-party API. Currently, I'm testing with Postman, but encountere ...

What sets apart the process of installing AngularJS and AngularJS Core using NuGet?

I am curious about the difference between these two packages in my packages.config file. Would it be advisable to uninstall one of them? <?xml version="1.0" encoding="utf-8"?> <packages> <package id="angularjs" version="1.3.15" targetFr ...

Executing multiple click events using JavaScript

I have recently started learning JavaScript and am experimenting with the following script: <script type="text/javascript"> $(document).ready (function() { $('#apply').click(function() { $('#applyinfo').toggle ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...