1

How can I make a utility helper function in JavaScript to check for existence of a variable to avoid the error Uncaught ReferenceError: testVar is not defined?

Below is what I am trying to do but failed!

/**
 * Utility Helper Functions
 */
var Utility = {

    /**
     * Check if a variable is empty or not
     * @param mixed value - variable to check if it is empty and exist
     * @return Boolean - true/false if a variable is empty or not?
     */
    isEmpty: function(value){
      //return (value == null || value === '');
      return (typeof value === 'undefined' || value === null);
    },
}

// comment var test out so it will not exist for test
//var testVar = 'dgfd';

// Uncaught ReferenceError: testVar is not defined
alert(Utility.isEmpty(testVar));
3
  • 1
    The error is thrown before you even get to your utility helper. In PHP this would be a fatal error. You pass a variable that does not exist. Commented Feb 27, 2016 at 20:12
  • @Horen I understand why it's doing it. I just was thinking there was a way in JS to have a function detect if if it existed in addition to the check for it being empty Commented Feb 27, 2016 at 20:18
  • There is a difference between a variable that exists with the value undefined and a variable that doesn't exist. There's no way to pass a variable that doesn't exist to your function. (You can test for non-existent globals by passing the variable name as a string and checking if it is a property of window, but you can't do that for local variables.) Commented Feb 27, 2016 at 20:20

1 Answer 1

3

You can't handle this inside the isEmpty function, since it throws the error before you get inside the function.

You could use a try / catch but that would defeat the purpose of the function.

You could simplify things and remove the whole function (which is not needed) like so:

if (typeof testVar !== "undefined") {
  console.log('The variable exists');
}

Object, Array

if( foo instanceof Array ) { 

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

3 Comments

Thanks for explaining. I was JUst hoping to possibbly avoid alway having to use the whole typeof testVar !== "undefined" syntax everytime but it seems its not possibble
@JasonDavis it is if you use object properties instead of variables
@JasonDavis: It seems the actual problem is that you are trying to access variables that don't exist. What's the context? You shouldn't be in such a situation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.