Zena Mesfin Zena Mesfin -4 years ago 60
Javascript Question

How to use values in parameter of invocation of the function?

I am not sure if the question has the right terms/words but I have the code and should explain the problem.



function canDrive(age,_yes,_no){
if (age >= 16) {

return _yes;
} else {

return _no;
}
}

function myFunction() {
document.getElementById("demo").innerHTML = canDrive(30,"YES WAY","NOWAY");
}
myFunction();

<p>Can he drive <span id="demo"></span></p>





The problem is that invocation where i do not have access is structured like this. It seems to be valid

canDrive(30)("YES WAY","NOWAY");


How can i access YES WAY and NOWAY ? in the above scenario? If I can understand how it works i can solve a big problem. Thank you

Answer Source

Based on my understanding of your question, I assume you are looking for this:

function canDrive(age) {
  return function(yes, no) {
    return age >= 16 ? yes : no;
  }
}

console.log(canDrive(30)("YES WAY", "NOWAY"));

canDrive returns a closure which returns one of the two supplied arguments based on age.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download