FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

[JavaScript]: Checking for undefined values

 


rohan2kool
Many times, I get the values of many things as undefined, generally while parsing strings. What i want to do is, using the if statement, check if a given variable is undefined or not. I've tried the following, but they don't work:

Code:

if(myvar == 'undefined') {
   //do something
}

if(myvar == "undefined") {
   //do something
}

if(myvar == undefined) {
   //do something
}

if(myvar == null) {
   //do something
}


Is there any function sort of thing to check the whether a given variable is defined or undefined...

thanks
poppitz
Hi,

try

Code:

if(typeof myvar == "undefined") {
   //do something
}
AftershockVibe
Hmm... if you're getting this from conversion ("casting") from strings to other data types it would be better practice to check the string beforehand for invalid characters.

ie If you are converting to an integer use a regular expression (or similar) to make sure the string only contains the characters 0-9 and nothing else. If this is not the case then either throw an error or strip out the invalid characters.
bladesage
rohan2kool wrote:
Many times, I get the values of many things as undefined, generally while parsing strings. What i want to do is, using the if statement, check if a given variable is undefined or not. I've tried the following, but they don't work:

Code:

if(myvar == 'undefined') {
   //do something
}

if(myvar == "undefined") {
   //do something
}

if(myvar == undefined) {
   //do something
}

if(myvar == null) {
   //do something
}


Is there any function sort of thing to check the whether a given variable is defined or undefined...

thanks


Try:
Code:
if(myvar == "")
{
//do something
}


That would return whether or not a variable is a null value.

To see if a variable is undefined altogether,

Code:
if(myvar)
{
//do something
}


This would return whether or not a variable, myvar, exists; ergo, whether or not it is defined. It performs the following action (in this case comment) if it exists.

To see if something is absolutely non-existent, use
Code:
if(!myvar)
{
//do something
}


That would say "if the variable 'myvar' is not defined, perform '//do something'"

Is that what you're looking for?
Reply to topic    Frihost Forum Index -> Scripting -> Others

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.