Return and callback in javascript function

Say I'm writing this function ...

var sayHi = function() {
  return "hi";
}

alert(sayHi()); will return hello.

Now, if I write it like this ...

var sayHi = function(callback) {
  callback("hi");
}

How to display hello using this function?

Based on the example here: http://nowjs.com/doc

+3
source share
6 answers

Try the following:

sayHi(function(msg){
    alert(msg)
});

Your new function sayHidoes not return a value, so you need to do an alert in the callback function.

0
source

You pass the sayHi function, so I imagine this:

sayHi(alert);
+4
source

:

var sayHi = function(callback) {
  callback("hi");
}

sayHi(function(message){
  alert(message);
});
+1
sayHi(function(value) {
    alert(value);
});
0
sayHi(function(msg) {
    alert(msg);
});

When using callbacks, you must invert your thinking process. Instead of writing the next operation first, you write the next operation last.

0
source

Here in the example, the callback is a function. Therefore, you must pass an argument to the function.

You can do this in two ways:

var some_fun = function(some_str) {
    alert(some_str);
}

var sayHi = function(callback) {
  callback("hi");
}

    sayHi(some_fun)

or you can pass a function when you call it:

var sayHi = function(callback) {
  callback("hi");
}

sayHi(function(some_str){
  alert(some_str);
});
0
source

All Articles