Search code examples
javascriptif-statementfunction-call

What does using a function name without parentheses do in an if statement in JavaScript?


For example:

function foo (parameter1, parameter2) {
    // does something
}

if (foo) {
    foo(parameter1, parameter2);
}

Calling a function without parentheses was talked about in a different question (In JavaScript, does it make a difference if I call a function with parentheses?), but I still don't understand what the above code does.

I'm asking because I'm trying to understand what if (drag) {..} does in this code: https://andreasrohner.at/posts/Web%20Development/JavaScript/Simple-orbital-camera-controls-for-THREE-js/


Solution

  • Your code defines a global function foo with two parameters.

    After that there's an if statement to check if foo is truthy(foo is your function and therefore truthy). So it calls the function foo. But be careful, if foo was not defined your code will throw a ReferenceError.

    A much better way to check if a function exists is:

    if (typeof foo === "function") { 
      // safe to use the function foo
    }