Basic callback function result

166
April 13, 2018, at 6:22 PM

I am trying to understand the callback concept.

When I do that:

var myCallback = function(data) {
 console.log(  'got data: '+data);
};
var usingItNow = function(callback) {
  callback('get it?');
};
usingItNow(myCallback);

I get that as output as expected:

got data: get it?

But when I do the below, I get undefined as output, why is that?

var myCallback = function(data) {
 return 'got data: '+data;
};
var usingItNow = function(callback) {
  callback('get it?');
};
console.log(usingItNow(myCallback));
Answer 1

You need to return from the usingItNow as well.

const myCallback = function(data) { 
    return 'got data: '+ data; 
}; 
 
const usingItNow = function(callback) { 
    return callback('get it?'); 
}; 
 
console.log(usingItNow(myCallback));

Answer 2

This has nothing to do with callback. You are printing out the result of a function call, but the usingItNow() function doesn't return anything, so the result is undefined.

To prove that it has nothing to do with callback, try to print out the call to a standard function that returns nothing and you will get undefined too:

function usingItNow(num) { 
  num = num + num; 
}; 
 
console.log(usingItNow(10));

Now, simply make the function return something and you will get it printed out:

function usingItNow(num) { 
  return num + num; 
}; 
 
console.log(usingItNow(10));

Which leads to what Suren mentioned in his answer, return the result of the callback to get it printed out:

const myCallback = function(data) { 
  return 'got data: ' + data; 
}; 
 
const usingItNow = function(callback) { 
  return callback('get it?'); 
}; 
 
console.log(usingItNow(myCallback));

Rent Charter Buses Company
READ ALSO
Casting a radio button with parseInt returns a string

Casting a radio button with parseInt returns a string

I have a set of radio buttons which are set using the below methodsAt the point of handleChange I'm casting the value to a integer if the target element is a radio button

233
Writing to a server file from a button click in a Jekyll project

Writing to a server file from a button click in a Jekyll project

As the title suggests, I do need to grab a button click from a user on a webpage, and use it to toggle a write on a file hosted on the server

177
Autobahn : Uncaught ReferenceError: when is not defined

Autobahn : Uncaught ReferenceError: when is not defined

I'm trying to use autobahnjs with ratchet

585
Check if span has class? [on hold]

Check if span has class? [on hold]

I'm trying to check if a span has a specific class visible

303