8

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?

6 Answers 6

16
 if (typeof anotherparm == "undefined")
Sign up to request clarification or add additional context in comments.

Comments

3

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

if (anotherparam) {...}

Comments

2

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

2 Comments

The real question is what do you get for "typeof z[100]", "z[100] === null", and "z[100] === undefined" ?
sure, that answers his question narrowly. The first is technically the best way to test (2nd fails, 3rd works but "undefined" can be reassigned)
2

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

var string_length = anotherparm.length;

1 Comment

Or indeed an Array, which is what he has here, in the same way.
1

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.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.