John Cooper
John Cooper

Reputation: 7621

Checking whether a variable is null or NOT

var DEST_VALUE = 1
var APPDAYS_AFTER = 2

}

How can i check whether the variable holds some value or not. When i do this, it does not work...

Upvotes: 0

Views: 2595

Answers (3)

Steffen
Steffen

Reputation: 2237

I assume you mean "holds some value" like in "the variable has been created so it exists", right? Otherwise, your approach works perfectly fine.

If you want to check whether a variable exists in javascript, you have to check its parent object for the property - otherwise the script will fail. Each object in javascript belongs to a parent object, even if it seems to be global (then, it belongs to the window object). So, try something like:

  if (window.DEST_VALUE) 
    // do something

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

Of course it doesn't do anything, because in your example DEST_VALUE resolves to true like APPDAYS_AFTER. Value that resolve to false when converted to a boolean in javascript are:

false
null
undefined
The empty string ''
The number 0
The number NaN (yep, 'Not a Number' is a number, it is a special number)

if you write

if(!DEST_VALUE){
    txtSiteId.value = fileContents.Settings.SiteID;
}

you write "if DEST_VALUE is not true do something" (in your case it does nothing). If you want to check if a variables hold a value:

if(DEST_VALUE !== undefined){
     //do something
}

Upvotes: 4

Andron
Andron

Reputation: 6621

I use such function to check if variable is empty or not:

function empty( mixed_var ) {
    return ( typeof(mixed_var) === 'undefined' || mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false );
}

Upvotes: 0

Related Questions