0

How would you check if the function that does exist and is defined, is empty or not? For example:

function foo(){
   // empty
}

function bar(){
   alert('something');
   // not empty
}

Is there a function or a a simple way to check this?

5
  • 2
    What would the practical use be? Commented Aug 2, 2012 at 16:40
  • Are you specifically interested in a JQuery way to do it? (JQuery != JS) Commented Aug 2, 2012 at 16:41
  • @Nico, well no, JS would of course also be fine. I just thought there would maybe be a jQuery function in existence already that I was overlooking. Commented Aug 2, 2012 at 16:45
  • @Juhana, checking if user assigned callbacks in my jQuery plugin meet requirements. Commented Aug 2, 2012 at 16:45
  • That's a quite... peculiar requirement. Commented Aug 2, 2012 at 16:47

2 Answers 2

3

It's not really very useful, and generally not a good idea, but you could do:

function foo(){

}

function bar(){
   alert('something');
   // not empty
}

console.log('foo is empty :' + isEmpty(foo));
console.log('bar is empty :' + isEmpty(bar));

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "")
   )[1].trim() === "";
}​

FIDDLE

If it's just to check a callback, the normal way would be just to check if the callback is a function:

if (typeof callback === 'function') callback.call();

EDIT:

To also disregard comments :

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\(\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
   )[1].trim() === "";
}​

FIDDLE

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, but won't work if there are comments inside the function.
No it won't, and then the function would'nt really be empty either!
Thanks for the lengthy answer! Guess there isn't a simple way to check and i'll just check if the callback is indeed a function.
1

A function could be empty but still be passed variables. This would error in adeneo's function:

function bar(t) { }

Modifying the regex, here is the same function with support for variables:

function isEmpty(f) {
  return typeof f === "function" && /^function [^(]*\([^)]\)[ ]*{(.*)}$/.exec(
     f.toString().replace(/\n/g, "").replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/g, '')
   )[1].trim() === "";
}​

Comments

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.