În php I would use this to see if a variable is set and then use that value, otherwise make it a zero:
$pic_action = isset($_POST['pic_action']) ? $_POST['pic_action'] : 0;
But what is the equivalent in javascript?
I want to check if an element exists in the document, and then if it does, add it to the variable, otherwise add some other value to it, here is what I have so far:
var areaOption = document.getElementById("element");
Thanks
5 Answers 5
var areaOption = document.getElementById("element") || some_other_variable;
Comments
isset() checks whether the variable is defined and not null. Javascript scoping rules being different from PHP, checking whether a variable is defined is harder. You can, on the other hand, determine if it is null:
if (areaOption === null) areaOption = ... ;
Then, there's the classic Javascript idiom using the lazy evaluation of ||:
areaOption = areaOption || ... ;
The latter does not check for the variable being null, merely if it's equivalent to false, which means the right-hand part will be evaluated even if the value is defined (and is 0 or ''), which may be unsafe if you rely on the types being valid.
Comments
The more verbose approach:
var c = document.getElementById("a") ? document.getElementById("a") : "b";
Or the shorter version:
var c = document.getElementById("a") || "b";
If you want to access a property, say innerHTML, on a given element, if the element exists; the first example can be re-written, like so:
var c = document.getElementById("a") ?
document.getElementById("a").innerHTML /*element exists: return innerHTML*/ :
"" /*element does not exist: return nothing*/;
... Without the comments:
var c = document.getElementById("a") ?
document.getElementById("a").innerHTML :
"";
Comments
document.getElementById("element") will return null if the element doesn't exist -- and something not-null if it exists.
Which means you should be able to do something like this :
var areaOption = document.getElementById("element");
if (areaOption) {
// element exists
} else {
// element doesn't exist
}
(You could also compare areaOption with null, instead of just checking if it's non-falsy)
I believe what you're trying to accomplish is something like this:
var dummy = null;
var areaOption = (dummy = document.getElementById("element")) ? dummy.value : 0;