0

New to javascript. I want to check if temp is a function or not. Also I would like to know why typeof won't work in this situation : Situation where a function is passed as a parameter. Understanding it is my purpose so no jQuery please. Appreciate all the help. Thanks

function getParams(foo, bar) {
  if (typeof bar === 'function') console.log("bar is a function");
  console.log(typeof bar); // string: because i returned string. But why not a "function" ? 
}

function temp(element) {
  return element;
}

function runThis() {
  getParams("hello", temp("world"));
}


runThis();
mwilson
  • 12,295
  • 7
  • 55
  • 95
Newbie_Android
  • 225
  • 2
  • 3
  • 12

1 Answers1

2

temp('world') returns a string so therefore you are passing in a string instead of a function.

did you mean to pass in temp instead?

function getParams(foo, bar) {
  if (typeof bar === 'function') console.log("bar is a function");
  console.log(typeof bar); // string: because i returned string. But why not a "function" ? 
}

function temp(element) {
  return element;
}

function runThis() {
  getParams("hello", temp("world")); // <-- temp("world") isn't a function. It's the result of a function
}

// Did you mean to do this?
function runThis2() {
  getParams("hello", temp);
}


runThis();
runThis2();

If you are wanting to also pass parameters to your passed in function, you could do something like this (there are multiple ways to accomplish this):

function getParams(foo, bar, functionParam) {
  if (typeof bar === 'function') 
  {
    console.log("bar is a function");
    const result = bar(functionParam);
    console.log('function result: ', result);
  }
  console.log(typeof bar); // string: because i returned string. But why not a "function" ? 
}

function temp(element) {
  return element;
}

// Did you mean to do this?
function runThis2() {
  getParams("hello", temp, 'my function param');
}

runThis2();
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • ahh.. i see. Thanks. But I need to pass parameters to the temp function. As in, : getParams(a1, a2, temp(a1,a2,"value")) to check. a1 and a2 need to be passed to the function, "temp" as parameters. – Newbie_Android Oct 15 '19 at 16:42
  • yea I will do that. Thanks. I had no idea I was passing a result of a function if i do that way. – Newbie_Android Oct 15 '19 at 16:46