Javascript nuances

Posted on Tuesday, November 20, 2007

Oh Javascript... you can't be intuitive can you?

I want to see if a function exists and then call it -

    if(decrementComments)
        decrementComments();

Wrong.

    if(typeof decrementComments == 'function')
        decrementComments();

Right.

Graffiti users of the world can have comments on their posts now. :)

Jayme

Comments

  • Ben Tiedt on 11.20.2007 at 2:55 PM
  • What's wrong with #1? I've used this hundreds of times. While its true that it only checks that the variable exists and is non-null (or zero or false), it should work for simple checks.

  • Jayme on 11.20.2007 at 3:17 PM
  • With #1, I get the following error if the function is not defined (IE and FF).

    decrementComments is not defined

    Line: if(decrementComments)

    If the function is there, it works fine.

    Jayme

  • Ben Tiedt on 11.20.2007 at 4:13 PM
  • Try if(window.decrementComments) instead -- when I've used this, it has always been against a member variable such as if(this._functionName).

  • steve on 6.15.2009 at 9:27 PM
  • thanks for shared

Leave a Comment


Search this site

Last 3 Tweets

  • @JasonBarile We will have to have a beer night at his house and play pool :)
  • @hkarthik I find the card easier than dealing with a check :)
  • I love JQuery, but all of the datatables that have to offer are nowhere near as good as the YUI one.