Home > Enterprise >  Function as an argument
Function as an argument

Time:02-05

five = function(parameter1) {
  console.log(parameter1)
}

five(function() {
    var x = 5;
    return x;
})

I have passed an anonymous function as an argument to the five function, why is this function not logging 5?

CodePudding user response:

five = function(parameter1) {
  console.log(parameter1())
}

five(function () {
    var x = 5;
    return x;
})

Change it like this, and it should work.

you did not call the function you just made a reference to it.

CodePudding user response:

five = function(parameter1) {
  console.log(parameter1()); // call the passed function
}

five(function() {
    var x = 5;
    return x;
})
  •  Tags:  
  • Related