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

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

Exploring the seamless integration of Material UI slider with chart js

Looking for guidance on syncing Material UI slider with chart js? I'm working on a line chart and hoping to have the x-axis value highlighted with tooltip as I slide the Material UI slider. ...

Conditional statement that includes Node.js scheduling function

I am currently working on a Node.js project and I need to execute a specific portion of conditional code after waiting for five minutes since the last piece of code executed. This action should only happen once, not on a daily basis or any other frequency. ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Initializing an Express app with JSON file loading

My movie-finding application relies on backend API calls to function. As part of the initialization process, I need to load two JSON files: one containing a list of languages for searching (lang.json) and another stored in the config variable that provides ...

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

Is it possible that data scraping with puppeteer consistently retrieves information solely from the initial page?

I'm facing an issue while trying to extract data from a website using puppeteer. Whenever I make a request for data, it always returns the information from the first page, even if I specify a different URL. Strangely, when I manually search for the sa ...

Stylist in Visual Studio Code for React applications

Whenever I try to save or format my React code using Ctrl + Shift + F, the formatting of the code below seems unusual. Is there a way to fix this issue? The original code is as follows: import logo from './logo.svg'; import './App.css&apos ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

There seems to be an issue with accessing /puffins/5f298d0ebcbaf254dcf282b3 at

Having trouble with my destroy route - it keeps returning an error. I've spent a lot of time trying to debug it but no luck yet. Can you lend a hand? All other CRUD routes are functioning correctly. //THE ROUTE app.delete('/puffins/:id', (re ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...

What are some methods to secure my API keys within my React application?

What steps can I take to secure my api keys in my react application? Should I incorporate something with express? My goal is to avoid creating any server-side components to handle the API calls. Currently, my backend is managed by firebase but I also uti ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

Guide on utilizing every array value during each iteration of a for loop, ensuring that the same number of values

Below is the equipos_seleccionados array: ["12 - v4", "100 - v500"] This is a preview of the frontend: When you input values in the head section, textboxes are generated automatically. Objective: Assigning the value 12 - v4 to the fi ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

Recharge Backbone prior to a lockdown

I'm currently utilizing a script within Backbone in a Cordova application (Android) that causes the app to freeze for 5 seconds, and unfortunately I am unable to find an alternative method. Due to this issue, I would like to display a loading message ...

Resetting the Angular provider configuration whenever the service is injected into a different location

Trying to wrap my head around a rather complex issue here. I have a service set up as a provider in order to configure it. Initially, this service has an empty array of APIs which can be dynamically added to by various configuration blocks. When adding API ...