0

I want to call a function inline from a variable, but respecting the case, when the variable is null / undefined or not a function.

var f;
if(typeof(f) == 'function') {
    f(); // don't get executed
}
f(); // this is of course not working, but it is executing

var fn = function() { console.warn('fn'); }
fn(); // working because fn is a function

Basically I want the if statement, with checking whether the variable is a function or not in one line.

I saw this and thought there has to something for undefined / non functions:

var screenSize = screen.width || 1024;

1 Answer 1

1

You can use a logical AND:

typeof f === 'function' && f();

The second operator is only evaluated if the first one is truish.

1
  • Nice. Is there a way to shorten typeof f === 'function' Commented Aug 1, 2013 at 23:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.