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 ?
Two reasons:
1) What if the variable is set by getting the contents of an empty input box?
Perhaps this is only done in certain cases, like when
someScenariois 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.
It’s no slower, has no real flaws, and is only a few characters more.
2) And most importantly, using
typeofmakes 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 usingtypeofmakes it perfectly clear what your conditional is looking for, and reduces the odds of mistakes later on.