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?
To check if a variable is not given a value, you would only need to check against undefined and null. This is assuming 0 , "" , and objects(even empty object and array) are valid "values".
The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator.
Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . The typeof operator returns a string that indicates the typeof of a value. If used with a string, the typeof operator returns "string" . Copied!
if (typeof anotherparm == "undefined")
An empty string evaluates to FALSE in JavaScript so you can just do:
if (anotherparam) {...}
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
you can check the number of charactors in a string by:
var string_length = anotherparm.length;
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With