How to check if a variable has a value in JavaScript?

I want to check if a JavaScript variable has a value.

var splitarr = mystring.split( " " ); aparam = splitarr [0] anotherparam = splitarr [1] //.... etc 

However, there may not be enough entries for the row, so later I want to test it.

 if ( anotherparm /* contains a value */ ) 

How to do it?

+4
source share
6 answers

In general, this is a kind of gray area ... what do you mean by "matters"? The null and undefined values ​​are valid values ​​that you can assign to a variable ...

The String split() function always returns an array, so use the length property of the result to find out which indexes are present. Out-of-range metrics will be undefined .

But technically (outside the context of String.split() ) you can do this:

 js>z = ['a','b','c',undefined,null,1,2,3] a,b,c,,,1,2,3 js>typeof z[3] undefined js>z[3] === undefined true js>z[3] === null false js>typeof z[4] object js>z[4] === undefined false js>z[4] === null true 
+2
source
  if (typeof anotherparm == "undefined") 
+10
source

An empty string evaluates to FALSE in JavaScript, so you can simply do:

 if (anotherparam) {...} 
+3
source

you can check the number of characters per line:

 var string_length = anotherparm.length; 
+2
source

One trick is to use the or operator to determine the value if the variable does not exist. Do not use this if you are looking for boolean " true " or " false "

 var splitarr = mystring.split( " " ); aparam = splitarr [0]||'' anotherparam = splitarr [1]||'' 

This prevents the error from being thrown if the variable does not exist, and allows you to set it by default or no matter what you choose.

+1
source

There are so many answers above, and you would know how to check the value of a variable, so I will not repeat it.

But the logic you are trying to write may be better written with a different approach, i.e. rather, looking at the length of the split array, rather than assigning the variable the contents of the array and then checking.

i.e. if(splitarr.length < 2) , then obviously anotherparam certainly does not contain a value.

So, instead of doing,

 if(anotherparam /* contains a value */ ) { //dostuff } 

You can do,

 if(splitarr.length >= 2) { //dostuff } 
+1
source

All Articles