Javascript check if a variable is set

Typically, I check if a variable is set with something like this:

if (variable !== '') {

   do something...

}

I know that there are other methods for testing type variables typeof, but I see no advantage - is this an appropriate way to check if a variable is set? Are there any issues with this that I should know about?

+5
source share
5 answers

Two reasons:

1) What if the variable is set by entering the contents of an empty input field?

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

, , , someScenario . , ​​ . false, true. , , .

.

if(typeof variable !== 'undefined')

, , .

2) , typeof , . , , , , . , typeof, , , .

+15

variable , , :

if (variable !== '') {

. , ? . undefined , "" (, null - ).

variable , , - , doesn ' t . , , , , , , , , , , JS, , , :

if (typeof variable != "undefined") {
+3

, true:

  • undefined
  • NULL
  • 0

, , false - .
, ?

+2

coffeescript, " " : http://coffeescript.org/

, - script, .

, . -, , , , " , variable, ", " -, ."

+2

This can be very subjective, but my recommendation is to avoid the code that needs to check whether a variable is set (aot has some value or type).

Consider this snipplet

var a=false;
if (some_condition) a="Blah";
if (typeof(a)=='string') ....
if (a===false) ...

this ensures that ait is always set, keeping it easily differentiable from '', nullor0

0
source

All Articles