Skip to content Skip to sidebar Skip to footer

How Can I Test Whether A Variable Has A Value In Javascript?

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 mi

Solution 1:

if (typeof anotherparm == "undefined")

Solution 2:

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

if (anotherparam) {...}

Solution 3:

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] === undefinedtrue
js>z[3] === nullfalse
js>typeof z[4]
object
js>z[4] === undefinedfalse
js>z[4] === nulltrue

Solution 4:

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

var string_length = anotherparm.length;

Solution 5:

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.

Post a Comment for "How Can I Test Whether A Variable Has A Value In Javascript?"