sidwelle
asked on
Correct way to test for the existence of an object w/JavaScript
What is the best way to test for the existence of an object w/JavaScript ?
We are using Mirth msg engine to move message, Mirth uses Rhino JavaScript to evaluate scripts and return values.
but we don't know the best way to evaluate the existence of an object.
Thanks
We are using Mirth msg engine to move message, Mirth uses Rhino JavaScript to evaluate scripts and return values.
but we don't know the best way to evaluate the existence of an object.
Thanks
var myObj;
if (myObj) { // code }
if (myObj == 'undefined') { // code }
if (myObj.length() > 0 ) { // code }
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
the "if" statement will let you code runs based on the condition specified, the condition will be evaluated whether that condition is true or not.
below is some tests for verification:
you should get a result like this:
Any other conditions that are not listed ?i think:
if (myObj) { // code }
or:if (typeof myObj !== "undefined") { // code }
should be enough to evaluate the existence of an objectbelow is some tests for verification:
<script>
var myObj;
try {
if (myObj) {
output("if (myObj) { // code } is working fine - result: true");
} else {
output("if (myObj) { // code } is working fine - result: false");
}
} catch (e) {
output("error evaluating condition: if (myObj) { // code }");
}
try {
if (typeof myObj !== "undefined") {
output("if (typeof myObj !== \"undefined\") { // code } is working fine - result: true");
} else {
output("if (typeof myObj !== \"undefined\") { // code } is working fine - result: false");
}
} catch (e) {
output("error evaluating condition: if (typeof myObj !== \"undefined\") { // code }");
}
try {
if (myObj == 'undefined') {
output("if (myObj == 'undefined') { // code } is working fine - result: true");
} else {
output("if (myObj == 'undefined') { // code } is working fine - result: false");
}
} catch (e) {
output("error evaluating condition: if (myObj == 'undefined') { // code }");
}
try {
if (myObj.length() > 0) {
output("if (myObj.length() > 0) { // code } is working fine - result: true");
} else {
output("if (myObj.length() > 0) { // code } is working fine - result: false");
}
} catch (e) {
output("error evaluating condition: if (myObj.length() > 0) { // code }");
}
function output(v) {
console.log(v);
}
</script>
you should get a result like this:
if (myObj) { // code } is working fine - result: false
if (typeof myObj !== "undefined") { // code } is working fine - result: false
if (myObj == 'undefined') { // code } is working fine - result: false
error evaluating condition: if (myObj.length() > 0) { // code }
ASKER
Thanks for the help.
ASKER
1. The object exists in any way ?
2. A numeric expression evaluates to anything other than 0 ?
3. A binary expression evaluates to 'true' ?
Any other conditions that are not listed ?
Thanks