tags:

views:

129

answers:

6

Below is a code snippet, where we retrieve a form value. Before further processing check if the value is not null..

//-- code snippet starts here

var val = document.FileList.hiddenInfo.value;
alert("val is "+val);  //-- this prints null which is as expected
if(null!= val)
{
   alert("value is "+val.length); //-- this returns 4
}
else
{
   alert("value* is null");
}

`
//-- ends here

Any ideas why it happens so.. ??

+2  A: 

because val is not null, just contains 'null' as string ;)

try to check with 'null'

if('null' != val)
    ......
ArsenMkrt
Thanks it helped..
ria
A: 

You should be using the strict !=, aka: !== so that if the user inputs "null" then you don't get to the else...

ItzWarty
A: 

Use !==, != will get you into a world of nontransitive javascript truth table weirdness.

Plynx
+2  A: 

Is it possible that the value of val is actually the string "null" rather than the value null?

ScottyUCSD
Thanks it helped..
ria
A: 

this will do the trick for you

if(!!val){

alert("this is not null")

}else{

alert("this is null")

}

A: 

The way you have written if check is nice trick and C++ developer use it for nice reason. JavaScript is good and friendly at null checking and if(obj) is enough for null checking.

I will suggest you to go through some basics about JavaScript types that will help as developer coming from TYPE specific word its main pain in understanding JavaScript.

Anil Namde