tags:

views:

1246

answers:

7

I want to test whether a JavaScript variable has a value.

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

However the string might not have enough entries so later I want to test it.

if ( anotherparm /* contains a value */ )

How do I do this?

+1  A: 

you can check the number of charactors in a string by:

var string_length = anotherparm.length;
John Isaacks
Or indeed an Array, which is what he has here, in the same way.
bobince
A: 
if(null!=anotherparam)

or

if(""!=anotherparam)
Dutow
+5  A: 
 if (typeof anotherparm == "undefined")
James Curran
+1  A: 

In general it's sort of a gray area... what do you mean by "has a value"? The values null and undefined are legitimate values you can assign to a variable...

The String function split() always returns an array so use the length property of the result to figure out which indices are present. Indices out of range will have the value undefined.

But technically (outside the context of String.split()) you could 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
Jason S
The real question is what do you get for "typeof z[100]", "z[100] === null", and "z[100] === undefined" ?
James Curran
sure, that answers his question narrowly. The first is technically the best way to test (2nd fails, 3rd works but "undefined" can be reassigned)
Jason S
A: 

One trick is to use the or operator to define a value if the variable does not exist. Don't use this if you're looking for boolean "true" or "false"

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

This prevents throwing an error if the variable doesn't exist and allows you to set it to a default value, or whatever you choose.

Diodeus
+1  A: 

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

if (anotherparam) {...}
J-P
A: 

So many answers above, and you would know how to check for value of variable so I won't repeat it.

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

i.e. if(splitarr.length < 2) then obviously anotherparam is surely 'not containing value'.

So, instead of doing,

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

you can do,

if(splitarr.length >= 2)
{
   //dostuff
}
Chandan .