Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript testing whether or not a variable is set

Tags:

javascript

Generally, I test whether or not a variable is set with something like this:

if (variable !== '') {

   do something...

}

I know there are other methods for testing variables like typeof but I don't see any advantage - is this an appropriate way to test whether or not a variable is set? Are there problems with it that I should be aware of ?

like image 444
Thomas Avatar asked Aug 19 '12 21:08

Thomas


2 Answers

Two reasons:

1) What if the variable is set by getting the contents of an empty input box?

if(someScenario){
    var variable = $('empty-box').val(); }

Perhaps this is only done in certain cases, like when someScenario is true. Later on, you want to check if that variable was set. Your means returns false rather than true. Point is, you can come up with scenarios where you get wrong answers.

There's just no reason not to do it the accepted way.

if(typeof variable !== 'undefined')

It's no slower, has no real flaws, and is only a few characters more.

2) And most importantly, using typeof makes it totally clear what you're asking. Readability is crucial, and if another programmer read the first code, they would think you were checking that it wasn't an empty string. The method using typeof makes it perfectly clear what your conditional is looking for, and reduces the odds of mistakes later on.

like image 70
Nick Avatar answered Oct 09 '22 18:10

Nick


If variable has been declared but might not have a value then your code:

if (variable !== '') {

tests if it is not the empty string. Is that what you want? An empty string might be a valid value. Better to test for undefined, or explicitly initialise it to a value that you can then treat as "invalid" (perhaps null, or whatever suits).

If variable has not been declared at all the above code would result in an error such that execution would stop at that point - you can't test the value of a variable that doesn't exist. So if, for example, you're trying to test a global variable that is created inside a function that may not have been called yet, or perhaps you're using several JS files and one needs to test a variable that may or may not have been created by one of the other files, then the only way to do it is with:

if (typeof variable != "undefined") {
like image 25
nnnnnn Avatar answered Oct 09 '22 18:10

nnnnnn