Click to See Complete Forum and Search --> : null or undefined


kusi
11-24-2003, 06:49 AM
which one should be used to check if any value exists for a js var?
var v1 = getsth-from-anywhere-hyperborians();

if (v1==null)

if (v1=='undefined') /(or) if (v1=="undefined")

if (v1==undefined) // is undefined a reserved word?

which should be used?

Gollum
11-24-2003, 07:25 AM
It depends a lot on where you are getting your value from.
If you define your variable this way...

var v1 = getsth-from-anywhere-hyperborians();

then chances are, v1 will have the value of NaN (or not a number) unless getsth, from and anywhere are already defined and have valid numbers themselves and the hyperborians() function returns a valid number too. Use isNan(v1) to test this.

If you define it like this...

var v1 = someFunction();

then the value in v1 will depend on the return value from the function. If the function doesn't return a value it will be undefined, otherwise it will be the value that gets returned.

kusi
11-24-2003, 07:36 AM
what is the use of isNaN?
i dont care if it is number or not.
var v1 is just an object!

is null and undefined the same thing?

Gollum
11-24-2003, 08:20 AM
null and undefined are not the same.

undefined is what you get when you declare a variable and don't assign it a value, like in this bit of code...

var v1;


null is a keyword in Javascript to indicate that the variable is pointing to nothing, but it must be assigned, like this...

var v2 = null;


What to do... unless you know it is not going to be undefined, you should test for both values...

if ( (v == undefined) || (v == null) )