2

I have been using jquery and javascript for a long time. I have rarely ever written javascript without jquery, and this instance requires me understand callbacks with javascript. Its a simple case, but I don't understand how it works. Not only do I want to get it working, I want to understand the callback.

const ALL_DATES = ["05/01/1992", "01/01/2017", "09/17/2010", "07/07/2017", "07/17/2017", "09/23/2013", "03/30/2012";


//console.log(ALL_DATES);


function filterDates(input) {
    // Do your filtering here and use ALL_Dates
    return input;
}


export function getDates(input, cb) {
    setTimeout(() => {
        cb(filterDates(input));
    }, 300);
};

First I create fake data in the constant: ALL_DATES. filterDates function will be used to do filtering to my specific criteria.

What I don't fully grasp is the usage of getDates function (in the case, this function has to be utilized) and what I will be using for the callback function. In jquery, for example, what I would do is use the .change to check for a change event on an input, and run the getDates function again.

Can someone please help me grasp and understand the usage of the callback here, and what purpose it has to serve?

Thank you!

4
  • You are missing the call to getDates Commented Aug 16, 2017 at 22:50
  • 4
    There's not much in jQuery that affects how you use callbacks. Commented Aug 16, 2017 at 22:51
  • I was reading another person using javascript and he explained it well. In jQuery you use callbacks and understand it works. When using callbacks outside of jquery, it helps to understand what they are doing and how to make them work. Commented Aug 16, 2017 at 22:52
  • 1
    "what I will be using for the callback function". That's entirely up to you. All this does is wait 300 ms, call filterDates(input), and then pass that result to the callback function you supply. Commented Aug 16, 2017 at 22:53

3 Answers 3

1

"What I don't fully grasp is the usage of getDates function (in the case, this function has to be utilized) and what I will be using for the callback function..."

The callback function will be whatever desires to receive the filtered dates. So whatever code calls getDates will presumably want to do something with the dates, and so will pass a callback that expects to receive those dates.

// Userland code
getDates(function(dates) {
  // User now gets to work with the list of dates that you filtered internally
  dates.forEach(d => console.log("The date is %s", d));
})

However, if there's nothing asynchronous going on, you could just have getDates() return the dates instead of receiving a callback function. In your case, the setTimeout provides async behavior, but barring any sort of async processing like that, you'd more likely just return them.

Sign up to request clarification or add additional context in comments.

1 Comment

It's asynchronous because for some reason he wants it done 300 ms later.
1

If you take out the node and the jQuery - and try and build a simplified version - you may have a quicker time to grok it. Maybe these will help. A callback is just a function passed to another function. 'higher order function' is a confusing way of marketing it. jQuery methods often have an optional 'callback' /anonymous function that can run AFTER whatever that method does is done. The syntax is something you get used to - but it fogs up the view... if you aren't aware of the methods arguments and true nature.

$(document).ready( function() {
  console.log('DOM ready');
});
// vs
function sayReady() {
  console.log('DOM ready again...');
}
$(document).ready(sayReady);


examples: https://jsfiddle.net/sheriffderek/b6jj5z2u/

For the most part now though... async stuff is much easier to reason about with promises or async/await techniques... say you get data from an API, and you don't want to try and 'do' anything with it until it is all there / callbacks are pretty tough to write all the logic for - comparatively.

console.clear();

var exampleArray = [2, 45, 63, 7, 9, 12];

function doubleInput(number) {
  return number * 2;
}

function iterateOverArray(array) {
  console.log('iterateOverArray');
  for (var i = 0; i < array.length; i++) {
    console.log('-', array[i] );
  }
  return true;
  // you should really be returning something...
}

iterateOverArray(exampleArray);


// this function accepts an array and a function to run on each item
// not far off from array.forEach()...
function iterateAndRunFunction(array, exampleCallback) {
  console.log('iterateAndRunFunction');
  var newArray = [];
  for (var i = 0; i < array.length; i++ ) {
    var manipulatedValue = exampleCallback( array[i] );
    newArray.push(manipulatedValue);
  }
  console.log(newArray);
  return newArray; 
  // you should really be returning something...
}

iterateAndRunFunction(exampleArray, doubleInput);



function saySomething(message) {
  console.log(message);
}

function doSomethingLater(functionToRun, waitTime) {
  console.log('wait ' + waitTime + 'ms');
  setTimeout( function() {
    saySomething('HI!!! sorry I took ' + waitTime + 'ms');
  }, waitTime);
}

doSomethingLater(saySomething, 3000);

Comments

1

A callback is a reference to a function (function A) that you hand over to another function (function B) so that function B can call function A when it decides to. Check this out:

const FIVE_MINS = 300000
const rightNow = new Date()

function getTime(startTime) {
    if (typeof startTime === 'undefined') startTime = new Date()
    alert(startTime.getHours() + ":" + startTime.getMinutes() + ":" + startTime.getSeconds())
}

getTime() is a function that alerts the user to the time that is passed to it as an argument, or if it receives no argument, the time at the moment it is called.

setTimeout() wants a function as its first argument so it can call that function in 5 minutes. If you were to do this:

setTimeout(getTime(), FIVE_MINS)

you would see the alert immediately because getTime() IS BEING CALLED in this expression. Don't do that. setTimeout() is expecting a function reference so that it can call getTime() itself when the time comes. There is two ways to reference a function.

If the function needs no arguments, you can just pass the name without the parens. That is a reference to a function and the function can be dealt with later.

setTimeout(getTime, FIVE_MINS)

Notice getTime() doesn't have an argument, so it is going to use whatever "now" is at the time setTimeout() calls it (5 mins from now). If your function needs arguments, you can reference the function in this way:

setTimeout(() => getTime(rightNow), FIVE_MINS)

In this case, I am passing in rightNow which is the datetime of when this file first started being parsed. So no matter how long setTimeout() waits, when it calls getTime() it will alert the user to the time it was when setTimeout started, pretty much.

Couple last things I'll mention is that this older syntax is equivalent to the example above:

setTimeout(function() {getTime(rightNow)}, FIVE_MINS)

You'd have to use the older syntax if you don't have a transpiler like Babel in your project to translate ES6 (new JS syntax).

And one last, last thing I'll mention, which is the most complex thing about callbacks, is that they can be called with arguments from within the function they have been handed over to, and you can intercept/add to/alter these arguments from the outer function before they get passed to the inner one if you need to. But I'd have to set up a much more complex example to show you that and I think your question only relates to the basic use of callbacks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.