1

It says: TypeError: myFunc is not a function

I want the output to be "I am happy, haha!".

I'm learning callback functions in JS.

function emotions(myString, myFunc) {
    console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
    var ha="";
    for(var i=0;i<val; i++) {
        ha=ha+"ha";
    }
    return ha;
};

emotions("happy",laugh(2));
Abhay av
  • 13
  • 1
  • 1
  • 3
  • See the dupetarget. `emotions` = `setTimeout`, `laugh` = the `setTimeout` callback. – T.J. Crowder May 10 '17 at 11:18
  • `emotions('happy', laugh)` willl work. Kind of. Doing `emotions("happy",laugh(2))` is essentially equal to `emotions("happy",'haha')`. For the callback you need to provide a function. So in your example you would do `emotions("happy",function(){return laugh(2);})` – Viliam Aboši May 10 '17 at 11:19
  • One of the important features of JavaScript is that it treats functions as data. In the trade, we say that functions are first class citizens. That is how callbacks work: you pass the function as a piece of data to another function. In JavaScript, then you sometimes call, execute, run the function, and you sometimes simply assign it. If you think of a function as a coffee maker, you sometimes want the coffee and you sometimes want the machine itself. _continued …_ – Manngo May 10 '17 at 11:26
  • … If you want the _result_ of the function (the coffee), you run it by adding parentheses to the name: `doit()`. If you want the function iteself (the coffee maker) you refer to it _without_ the parentheses. That was your mistake: `laugh(2)` is the _result_ of the function, not the function itself. If you want it to be a callback, it needs to be `laugh` without the parentheses. The only other problem is that you can’t simply pass additional parameters with a callback, so you can’t simply include the `2`. – Manngo May 10 '17 at 11:33
  • @Manngo Wow. Thanks a lot for explaining 'callback' beautifully. – Abhay av May 10 '17 at 11:54

1 Answers1

3

Try this:

emotions("happy", laugh);

You're having that issue because you're no passing the function itself, but it's result as the parameter. When you do laugh() you are running the function, not using it's reference, hence, you're passing it's result instead.

The call will the executed inside the emotions function as laugh(2), so that's the correct way.

function emotions(myString, myFunc) {
    console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
    var ha="";
    for(var i=0;i<val; i++) {
        ha=ha+"ha";
    }
    return ha;
};

console.log(emotions("happy",laugh));
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105