1

I want to know whether a function is exist or is defined before i call it.

I have this line of code:

function renderView(){
 // some code
}
JahangirAhmad
  • 164
  • 2
  • 4
  • 8

1 Answers1

3

You can check the typeof, it returns undefined if it's not defined or out of scope, and function if it's a function

if ( typeof renderView == 'function' ) {
    // it exists
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • THANK YOU for using typeof as an operator and not a function like all the other fools :) – crempp Dec 21 '13 at 06:02
  • `//Simple function that will tell if the function is defined or not function is_function(func) { return typeof window[func] !== 'undefined' && $.isFunction(window[func]); } //usage if (is_function("myFunction") { alert("myFunction defined"); } else { alert("myFunction not defined"); }` – Muhammad Tahir Apr 23 '15 at 13:16
  • That uses jQuery and assumes the function is defined in the global scope ? – adeneo Apr 23 '15 at 14:44